Python for Loops: range(), enumerate() and zip()
A for loop runs its block once for each item in a sequence. Python's for is really "for each": you do not manage a counter yourself, you just name a variable that receives each item in turn. It works on anything iterable, including lists, strings, tuples, dictionaries, sets, files and ranges.
Looping over a collection
for lang in ["Python", "SQL"]: assigns "Python" to lang, runs the indented body, then assigns "SQL" and runs it again. The loop variable is an ordinary name and still exists after the loop ends, holding the last item.
Counting with range()
When you need numbers rather than items, use range(). range(3) produces 0, 1 and 2, stopping before the end value, just like slices. range(start, stop) sets the first number, and a third argument sets the step, so range(2, 11, 4) gives 2, 6 and 10. A range does not build a list in memory; wrap it in list() if you want to see the values.
Expected output
I am learning Python I am learning SQL 0 1 2 [2, 6, 10] 1+2+3+4+5 = 15 1 a 2 b 3 c Ava: 91 Liam: 78
The end=" " argument tells print() to finish with a space instead of a new line, so the numbers stay on one row; the bare print() after the loop ends that row.
enumerate() and zip()
Beginners often write for i in range(len(items)): to get positions. Python has a cleaner tool: enumerate(items) yields pairs of (index, item), which you unpack directly in the loop header. Pass start=1 for human-friendly numbering.
zip(a, b) walks two (or more) sequences side by side and yields tuples of matching items. It stops at the shortest input, so mismatched lengths do not crash, but data at the end of the longer list is silently skipped.
Looping over a dictionary
Looping over a dict yields its keys. To get both parts, loop over d.items() and unpack: for name, price in prices.items():.
Common mistakes
- Expecting
range(1, 5)to include 5. It stops at 4. - Modifying a list while looping over it, which skips items. Loop over a copy or build a new list.
- Forgetting the colon after the loop header, or forgetting to indent the body.
Summary
for x in iterable:runs the body once per item.range(stop),range(start, stop, step)generate numbers and excludestop.enumerate()adds an index;zip()pairs items from several sequences.
Quiz: for loops and range()