3 · Work with collections · 10 MIN
Repeat with a loop
A loop applies an operation to each item.
for n in values visits each value. Keep an accumulator outside the loop so it survives every iteration. Use consistent indentation. Summing n numbers takes O(n) time and O(1) extra space.
Count the coins in a jar by adding each coin to a running total.
Read the example
total = 0
for n in [2, 3, 4]:
total = total + n
print(total)Check the expected output
9
Your challenge
Return the sum of all numbers in input. An empty list sums to zero.
Common trap
Resetting total inside the loop loses earlier additions.
Next lesson: Select matching items →