Sub topic 9
Looping over a list
This chapter assumes you can write a basic for loop, index and slice a list, and know that lists are mutable. It covers how iteration over a list works, the idioms Python provides for it, and the bugs that appear when the list changes during the loop.
The basic for loop
A for loop visits each item of a list in order, from index 0 to the last index. On each pass it binds the loop variable to the next item.
colors = ["red", "green", "blue"]
for color in colors:
print(color)This prints red, green and blue, one per line. You get the items themselves, not their positions. Prefer this form whenever you only need the values.
Two facts about the loop variable matter later:
- The variable stays alive after the loop ends and holds the last item.
- If the list is empty, the body never runs and the variable is never assigned. Reading it afterwards raises
NameError(or silently uses an older value if the name existed before).
What happens under the hood
A for loop does not index the list directly. It asks the list for an iterator, then calls next on it until the iterator signals that it is finished.
it = iter([10, 20])
print(next(it)) # 10
print(next(it)) # 20
print(next(it, "done")) # doneWithout the default argument, the third next call raises StopIteration. A for loop catches that exception and exits quietly.
A list iterator stores two things: a reference to the list and the next position to read. It does not take a snapshot. If the list changes while the loop runs, the iterator sees the changed list. This explains the bugs in the section on modifying a list during iteration.
Note that the check against len(list) happens on every pass, using the list's current length.
Getting the index with enumerate
Sometimes you need the position as well as the value. Beginners often write for i in range(len(colors)) and then colors[i]. It works, but enumerate is shorter and avoids index mistakes.
colors = ["red", "green", "blue"]
for i, color in enumerate(colors, start=1):
print(i, color)The output is:
1 red
2 green
3 blueenumerate yields (index, item) pairs, and the for statement unpacks each pair into two names. The start argument changes only the number reported. It does not skip items.
Looping over two lists with zip
zip walks several lists in step and yields tuples of matching items.
names = ["Ana", "Ben", "Cy"]
scores = [90, 85, 77]
for name, score in zip(names, scores):
print(f"{name}: {score}")By default zip stops at the end of the shortest list and drops the extra items without any warning. If the lists should have the same length, pass strict=True (Python 3.10 and later). A length mismatch then raises ValueError instead of hiding a data problem.
names = ["Ana", "Ben", "Cy"]
scores = [90, 85]
try:
for name, score in zip(names, scores, strict=True):
print(name, score)
except ValueError as error:
print("Mismatch:", error)The loop prints the first two pairs, and then the error is raised when zip finds that names still has an item.
Unpacking and nested lists
If each item is itself a sequence, you can unpack it in the loop header.
pairs = [(1, "a"), (2, "b"), (3, "c")]
for number, letter in pairs:
print(number, letter)For a list of lists, use one loop per level.
grid = [[1, 2, 3], [4, 5, 6]]
for row in grid:
for value in row:
print(value, end=" ")
print()This prints 1 2 3 on the first line and 4 5 6 on the second. The outer variable row is the inner list itself, not a copy, which matters in the next section.
Reversed and sorted order
Two built-in functions let you loop in a different order without changing the list.
colors = ["red", "green", "blue"]
for color in reversed(colors):
print(color) # blue, green, red
for color in sorted(colors):
print(color) # blue, green, red
print(colors) # ['red', 'green', 'blue']reversed returns a lazy iterator that reads the list from the end. sorted builds a new sorted list. The original list is unchanged in both cases. Do not write for x in colors.sort():. The sort method returns None, so the loop raises TypeError.
Changing items while you loop
Rebinding the loop variable does not change the list. The loop variable is just a name that points at the current item.
nums = [3, 4, 5]
for n in nums:
n = n * 2
print(nums) # [3, 4, 5]To replace items, assign through the index.
nums = [3, 4, 5]
for i, n in enumerate(nums):
nums[i] = n * 2
print(nums) # [6, 8, 10]Replacing an item at an existing index does not change the list's length, so it is safe during a loop.
Mutating an item in place behaves differently when the item is itself mutable.
grid = [[1], [2]]
for row in grid:
row.append(0)
print(grid) # [[1, 0], [2, 0]]Here row and the list inside grid are the same object. A method call on row therefore changes the data in grid.
Modifying a list during iteration
Adding or removing items while looping over the same list is the most common iteration bug. Because the iterator tracks a position, removing an item shifts the later items left, and the iterator then skips the one that moved into the current slot.
nums = [1, 2, 2, 3, 4, 4]
for n in nums:
if n % 2 == 0:
nums.remove(n)
print(nums) # [1, 2, 3, 4]The intended result is [1, 3]. Python raises no error, so the bug is easy to miss.
Appending during a loop is also dangerous. If every pass adds an item, the iterator never reaches the end and the loop runs forever.
There are three reliable fixes.
- Build a new list with a comprehension and rebind the name.
- Iterate over a copy and change the original.
- Collect the changes first, then apply them after the loop.
nums = [1, 2, 2, 3, 4, 4]
# Fix 1: build a new list
odds = [n for n in nums if n % 2 != 0]
print(odds) # [1, 3]
# Fix 2: loop over a shallow copy, modify the original
for n in nums[:]:
if n % 2 == 0:
nums.remove(n)
print(nums) # [1, 3]The first fix is usually the clearest and the fastest. Comprehensions are covered in the next chapter.
Index-based loops with while
A while loop with a manual index is rarely needed, but it is the right tool when the step size or the list itself changes as you go.
stack = [1, 2, 3]
while stack:
item = stack.pop()
print(item) # 3, 2, 1Here the loop condition is the list's truthiness. An empty list is false, so the loop ends when the list is empty. This is safe because the loop does not use an iterator that holds a stale position. Each pass reads the current state of stack.
Stopping early with break and else
break leaves the loop immediately. A for loop can also have an else block, which runs only if the loop finished without hitting break. It suits search loops.
nums = [4, 8, 15, 16]
for n in nums:
if n > 10:
print("found", n)
break
else:
print("nothing above 10")This prints found 15. If no item exceeded 10, it would print nothing above 10 instead. For a plain yes-or-no test, any(n > 10 for n in nums) is shorter.
Choosing the right form
| You need | Use |
|---|---|
| Each value | `for x in items` |
| Each value and its position | `for i, x in enumerate(items)` |
| Items from two lists together | `for a, b in zip(xs, ys)` |
| Reverse order, list unchanged | `for x in reversed(items)` |
| Sorted order, list unchanged | `for x in sorted(items)` |
| A filtered or transformed new list | A list comprehension |
| To empty the list as you go | `while items:` with `pop` |
Common mistakes
- Using
range(len(items))whenenumerateor a plain loop would do. - Expecting
n = n * 2to update the list. - Calling
remove,insertorappendon the list being iterated. - Passing the result of
sort()orreverse()to a loop. Both returnNone. - Forgetting that
zipsilently truncates to the shortest input. - Reading the loop variable after an empty list was looped over.
Exercise
What does this code print, and why? values = [3, 4, 5] for v in values: v = v * 2 print(values)
Show answer
It prints [3, 4, 5]. The assignment v = v 2 rebinds the name v to a new integer, and the list still refers to the original integers. To change the list, assign through an index, for example with enumerate: for i, v in enumerate(values): values[i] = v 2.
Exercise
Given prices = [10, 20, 30] and labels = ["a", "b", "c"], write a loop that prints each label with its price, numbered from 1, for example "1 a 10". Make it raise an error if the lists differ in length.
Show answer
for number, (label, price) in enumerate(zip(labels, prices, strict=True), start=1): print(number, label, price). The zip call pairs the items and strict=True raises ValueError on a length mismatch. The enumerate call numbers the pairs from 1, and the loop header unpacks the nested tuple.