Accumulate values in a loop
Reach for each comma and return to your resting position. · 132 words
A loop repeats an operation for each item in a collection. Suppose a Python list contains the numbers two, four, and one. Start a total at zero and add each item to it in order. The total moves through two and six before ending at seven. This operation is a sum.
Write the running total immediately before and immediately after each addition. Before the last item it is six; after the last item it is seven. That observation suggests a rule you can check at every step: the total should equal the sum of the items already processed. Try the same loop with an empty list. The body runs zero times, so the initial zero becomes the answer. Testing that case checks whether the initialization makes sense independently of any particular item.
Check your recall
What total appears after the second item?
Check your answer
Six, because the first two items are two and four.
Worked exercise
Trace the value of total after each pass through this Python loop.
total = 0
for count in [2, 4, 1]:
total += countCheck your reasoning
The successive totals are 2, 6, and 7.
Sources and credits
Original KeyTouch lesson. Background reading · Python Software Foundation · Python tutorial.