Concepts / Understanding for Loops and Iteration

Understanding for Loops and Iteration

The central pattern is initialize before the loop, update inside the loop, and use the final value after the loop.

  • Programming
Interactive lab

Try it: Loop Tracer

How a Python for loop visits each item in turn, and how an accumulator variable (a total, a count, a best-so-far or a result list) changes on every iteration.

How it works

  1. Initialise the accumulator before the loop.
  2. Each iteration, the loop variable takes the next value from the list.
  3. An if inside the loop decides whether to update the accumulator.
  4. After the last item the loop ends and the accumulator holds the answer.

Default run (13 steps): values = [4, 9, 2, 7, 5]. Run the loop one statement at a time. … The loop has used every value. print(total) shows 27.

Simplified: A model of five fixed loop programs (sum, count, maximum, minimum, filter) run on your list — it steps the program exactly as Python would, but it does not run Python.

Educational simulation

Loading the simulation…

Why State Matters

A for loop processes a list one item at a time. That is enough when each item can be handled independently, but many tasks require information from earlier iterations. You may need to know how many items have been seen or what total has been built so far. An accumulator is the variable that preserves this information: it starts before the loop, changes during each iteration, and contains the final result when the loop ends.

Key point

The central pattern is initialize before the loop, update inside the loop, and use the final value after the loop.

A Loop Visits Each Item

When a for loop runs over a list, one iteration processes one item and then the loop moves to the next item. The loop's iteration variable identifies the current item. The loop continues until every item in the list has been processed. An accumulator gives the loop a way to remember a result across those separate passes.

itemslistitem 1process current itemLoop endsall items processednext itemprocess current itemvisitmove torepeatno items remain
What happens as a for loop visits each item, and when does it stop?

Counting Processed Items

A counting loop answers how many items have been processed. Set a counter to zero before the loop. During every iteration, increase the counter by one. The current item's value does not matter, because every item contributes exactly one to the count. After the loop finishes, the counter represents the total number of items seen.

python
Output
4
count0 items processed11 item processed22 items processed33 items processed44 items processed+1+1+1+1
How does the counter map to the number of items processed after each iteration?

The iteration variable item is present in the example because the loop needs a name for the current list item. The counting operation itself does not use item. Each pass contributes one item to the count, so the counter changes from zero to one, then two, then three, and finally four.

Summing a Running Total

A summing loop uses the current item's actual value. Set the total to zero before the loop, then add the current item to total during every iteration. Unlike a counting loop, which always adds one, a summing loop may add a different amount on each pass. The accumulator therefore represents the sum of all items seen so far.

python
Output
154
3current valuetotalrunning sum154final total41current value12current value28current value50current value20current valueaddaddaddaddaddaddafter all values
How does each list value move into the accumulator to produce the final total?

Tracing the Accumulator

Tracing means recording the accumulator after every update. Begin with total equal to zero. The first value is 3, so total becomes 3. The next value is 41, so total becomes 44. Continuing this process gives 56 after adding 12, 84 after adding 28, 134 after adding 50, and 154 after adding 20. Because each new value uses the previous total, the accumulator never resets during the loop.

IterationCurrent valueTotal beforeTotal after
Startnone00
1303
241344
3124456
4285684
55084134
620134154

The total after each iteration equals the previous total plus the current value.

0before loop3after 344after 4156after 1284after 28134after 50154after 20+3+41+12+28+50+20
How does the accumulator change after each item, and what value does it contain when the loop ends?
Key point

At any point in a summing loop, the accumulator should equal the sum of the items processed so far. This gives you a practical check for detecting an incorrect update or reset.

Keeping the Update Correct

  • Common mistake

    Initializing the accumulator inside the loop

    What it looks like
    for value in values:
        total = 0
        total += value
    Why it fails

    The variable is reset on every iteration, so earlier values are discarded instead of being retained.

    Do this instead

    Set total to zero before the loop and update it inside the loop.

  • Common mistake

    Adding one when the task is to compute a sum

    What it looks like
    for value in values:
        total += 1
    Why it fails

    Adding one counts items, but it does not add their actual numeric values.

    Do this instead

    Use total += value for a summing loop.

  • Common mistake

    Adding the current value when the task is to count

    What it looks like
    for item in items:
        count += item
    Why it fails

    A counting loop should give every item the same contribution of one, regardless of the item's value.

    Do this instead

    Use count += 1 for each processed item.

Choosing Built-In Functions

Manual loops are valuable because they reveal the counting and accumulation patterns. However, Python provides built-in functions for these two basic tasks. len() returns the number of items in a list, and sum() returns the total of numeric items. For ordinary counting and summing, these functions are clearer, shorter, and more efficient than writing a manual loop.

python
Output
4
154
TaskManual patternBuilt-in choicePractical guidance
Count list itemsInitialize a counter and add one per iterationlen()Use len() for basic list counting
Sum numeric itemsInitialize a total and add each current valuesum()Use sum() for basic numeric totals

Manual loops teach the underlying pattern; len() and sum() are the practical choices for these specific tasks.

Practice the Trace

EASY

Given values = [5, 8, 2], write a manual summing loop. Before running it, predict the value of total after each iteration. Then trace the accumulator and identify its final value.

Hints
  • Initialize total to zero before the loop.
  • Add the current value to total on every iteration.
  • The value after an iteration should equal the sum of all values processed so far.
Worked example

Tracing a Three-Item Sum

Find the accumulator values for values = [5, 8, 2] when total starts at zero and each current value is added.

  1. 1
    Start

    total is 0 before any item is processed.

  2. 2
    First iteration

    Add 5 to 0, giving total = 5.

  3. 3
    Second iteration

    Add 8 to 5, giving total = 13.

  4. 4
    Third iteration

    Add 2 to 13, giving total = 15.

Result

The final accumulator value is 15.

Key Takeaways

  1. 1
    An accumulator starts before a loop, changes during each iteration, and holds the final result afterward.
  2. 2
    A counting loop adds one for every item, so its counter represents the number of items processed.
  3. 3
    A summing loop adds the current item's value, so its accumulator represents the running sum.
  4. 4
    Tracing the accumulator after every iteration helps verify that the update is correct and that the value never resets unexpectedly.
  5. 5
    Use len() for basic list counts and sum() for totals of numeric items; use manual loops to learn the pattern and for tasks without a direct built-in function.

At a glance

  • A for loop processes one list item per iteration.
  • Counting uses a counter initialized to zero and incremented by one.
  • Summing uses an accumulator initialized to zero and updated with the current value.
  • Tracing each intermediate value exposes mistakes and confirms the final result.
  • Python's len() and sum() are clearer choices for basic counting and summing.

More concepts starting with U