Stockertim Dictionary · Technology
For loop
Also called for statement, Python for loop, iterating over a collection
In short
A block of code that repeats the same steps once for each item in a collection, such as each number in a list or each row of a file.
- Beginner
- Concept
- Checked
In detail
A for loop applies the same instructions to every item in turn. In Python it reads for item in collection: followed by an indented block. On each pass the name item refers to the next value, and the indented lines run once with it. When the collection is used up, the program carries on with the first line after the block.
A common pattern is the running total. total = 0 is set before the loop, and inside it total = total + amount adds each amount in turn; after the loop, total holds the sum. The same shape counts items that meet a condition, collects matching values into a new list or finds the largest value seen so far.
To repeat a fixed number of times, Python uses range. range(5) produces 0, 1, 2, 3 and 4, five values starting at zero and stopping before 5, and range(1, 13) produces the months 1 to 12. enumerate(items) gives each item together with its position, and zip(a, b) walks two lists side by side, which avoids handling indexes by hand.
Loops go wrong in recognisable ways. An accumulator reset inside the loop instead of before it ends up holding only the last value. Indentation decides what belongs to the loop, so a line indented one level too far runs on every pass rather than once. Changing a list while looping over it skips items. For whole columns of data, pandas operations are usually clearer and faster than a loop over rows.
Worked example
A bakery in Kumasi adds up the loaves sold on each of six days using a loop.
loaves = [120, 80, 100, 90, 110, 100]andtotalstarts at 0.- The loop adds each day's figure in turn: 120 + 80 + 100 + 90 + 110 + 100 = 600
- Average per day: 600 / 6 = 100
The loop gives 600 loaves for the week, matching sum(loaves), which is a useful cross-check.
In practice
Analysts write loops to process each file in a folder, run the same report for each region, or retry a download several times. When an AI assistant writes a loop, a quick check is to run it on three or four items whose answer is known and compare the result.
Watch out
rangestops one before its end value;range(1, 12)gives eleven months, not twelve.- Setting the running total to zero inside the loop instead of before it leaves only the final item.
Learn it properly
Official sources
- Quality assurance of code for analysis and research · Government Analysis Function
Facts last checked on 9 November 2026.
Education, not advice: the Stockertim Dictionary explains what terms mean. It never recommends buying or selling anything.