Sub topic 3
Why range(len(seq)) and manual counters get awkward
This chapter assumes you can write a basic for loop over a list, index into lists and tuples, and call functions such as len() and range(). It explains why the two usual ways of tracking position in a loop cause trouble. The next chapters show the replacement.
The two patterns
Sometimes a loop needs the position of each item as well as the item. Most people who learn Python through other languages write one of two things.
The first pattern loops over the indexes and looks up each value:
fruits = ["apple", "banana", "cherry"]
for i in range(len(fruits)):
print(i, fruits[i])The second keeps a counter variable next to the loop:
fruits = ["apple", "banana", "cherry"]
i = 0
for fruit in fruits:
print(i, fruit)
i += 1Both print the same three lines, and both work. The problems appear as the loop grows.
Problem 1: the code says more than it means
In the range(len(fruits)) version, you build a sequence of numbers from the length, then use each number to look the item up again. The loop variable i is only a way to reach fruits[i]. A reader has to decode three steps to see that you want each item with its position.
Python's for loop already hands you items directly. The index pattern throws that away and then rebuilds it by hand.
Problem 2: off-by-one errors
You choose the bounds yourself, so you can choose them wrongly. Two common slips:
fruits = ["apple", "banana", "cherry"]
# Skips the first item
for i in range(1, len(fruits)):
print(i, fruits[i])
# Raises IndexError on the last pass
try:
for i in range(len(fruits) + 1):
print(i, fruits[i])
except IndexError:
print("ran past the end")The first loop silently drops "apple". The second fails loudly, but only after it has already printed all three real items. The silent version is the worse one because nothing tells you the output is wrong.
Problem 3: the counter drifts
A manual counter must be updated on every pass. Any early exit from the loop body can skip the update. This happens often with continue:
lines = ["alpha", "", "gamma"]
position = 0
for line in lines:
if not line:
continue # skips the increment below
print(position, line)
position += 1The output is 0 alpha and 1 gamma. But "gamma" sits at index 2 in the list. Whether this is a bug depends on what you meant. If you wanted the real position, the counter has drifted. If you wanted a count of non-empty lines, the name position is misleading. In both cases the meaning of the number depends on where the += 1 line sits, and a later edit to the loop can change it without any visible warning.
The counter also exists as a separate variable that survives after the loop ends. Its final value is easy to misuse later.
Problem 4: it only works on indexable sequences
range(len(x)) needs x to support both len() and x[i]. Many iterables support neither: generators, file objects, and the results of map() and filter().
squares = (n * n for n in range(4))
try:
for i in range(len(squares)):
print(i, squares[i])
except TypeError as error:
print(error)This prints object of type 'generator' has no len(). The for item in squares form would have worked, since a for loop only needs an iterable. The index pattern asks for more than the loop needs. You would have to convert the generator to a list first, which stores every item in memory.
Problem 5: parallel lists multiply the noise
The pattern gets worse when you walk two lists together:
names = ["Ada", "Grace", "Linus"]
scores = [95, 88, 91]
for i in range(len(names)):
print(names[i], scores[i])Now i appears twice, and len(names) quietly assumes scores has the same length. If scores is shorter, you get an IndexError. If scores is longer, the extra values are ignored without any message. The code does not show that the two lists are meant to line up.
How the problems add up
The table below lists each problem with its cause.
| Problem | Cause | Result |
|---|---|---|
| Hard to read | Index is only a way to reach the item | Reader decodes three steps |
| Off-by-one | You write the bounds | Skipped or missing items, or `IndexError` |
| Counter drift | Increment is separate from the loop | Wrong numbers after `continue` or edits |
| Limited input | Needs `len()` and `[i]` | `TypeError` on generators and files |
| Parallel lists | Index used in several places | Silent mismatches |
The next diagram shows how a manual counter can fall out of step with the loop.
What a better tool needs
Each problem points to the same fix. The loop should produce the position and the item together, from one source, with no bounds to write and no counter to maintain. It should also work on any iterable. Python has a built-in for this: enumerate. Because it yields pairs, you will first need to unpack tuples in the loop header, which the other chapters in this tutorial cover.
Exercise
A loop uses count = 0, then count += 1 at the bottom of the body, and the body contains if item is None: continue near the top. For the list ["a", None, "c"], what does count equal when "c" is processed, and why might this be a bug?
Show answer
count is 1 when "c" is processed. The continue skips the increment for None, so the counter does not advance for that item. If you wanted the position of "c" in the list, which is 2, the counter is wrong. The result depends on where the increment sits, which is the fragile part of manual counters.
Exercise
Why does for i in range(len(x)): print(x[i]) fail when x is a generator, while for item in x: print(item) works?
Show answer
A generator has no length and does not support indexing, so len(x) raises TypeError. A plain for loop only needs an iterable, and a generator is one.