Sub topic 3
Why range(len(seq)) and manual counters get awkward
This chapter explains why two common loop styles cause trouble in real code. One is for i in range(len(seq)). The other is a hand-maintained counter variable. Both work in simple cases. As the code grows, they produce bugs and noise that enumerate and zip avoid. The following chapters show those replacements. This chapter covers the problems they solve.
You should already be comfortable with these topics:
- Basic Python syntax and
forloops over lists. - Lists, tuples, and dictionaries.
- Calling functions and using their return values.
- The idea from the previous chapters that a
forloop consumes an iterable and that tuples can be unpacked in the loop header.
The pattern you see everywhere
Many programmers arrive in Python from languages where a loop is written with an index variable. In C or Java, for (int i = 0; i < n; i++) is the normal way to walk a list. In Python the direct translation looks like this:
fruits = ["apple", "banana", "cherry"]
for i in range(len(fruits)):
print(i, fruits[i])Output:
0 apple
1 banana
2 cherryThis is correct and it runs. The question is what it costs you. To understand the costs, look at what the loop does step by step.
len(fruits)is evaluated once, giving3.range(3)produces the integers0,1,2.- On each pass,
iis bound to the next integer. fruits[i]looks the item up again by position.
The loop never touches the list directly. It iterates over numbers, and you then use those numbers to reach back into the list. The list and the loop variable are connected only by your own discipline.
What goes wrong with range(len(seq))
Noise hides intent
Compare the loop above with how you would say it in English: "for each fruit, with its position, print both." The index version says: "for each number from zero to the length, fetch the item at that number." The reader must reconstruct the intent from the mechanics. Each extra expression, such as len(...), range(...), and fruits[i], is a place to make a typo or to misread.
Off-by-one errors
Because you control the bounds, you can get them wrong. Two common mistakes:
fruits = ["apple", "banana", "cherry"]
# Too far: i reaches 3, but the last valid index is 2
try:
for i in range(len(fruits) + 1):
print(fruits[i])
except IndexError as error:
print("IndexError:", error)
# Too short: starts at 1, so "apple" is silently skipped
for i in range(1, len(fruits)):
print(fruits[i])The first loop prints three fruits and then fails with IndexError: list index out of range. The second loop does not fail at all. It silently skips the first item. Silent wrong answers are worse than crashes, and index arithmetic produces them easily.
It only works on sequences
range(len(x)) followed by x[i] requires two things from x: it must support len(), and it must support indexing by integer. Many iterables fail one or both tests.
def read_lines():
yield "first"
yield "second"
lines = read_lines()
try:
for i in range(len(lines)):
print(i, lines[i])
except TypeError as error:
print("TypeError:", error)
colors = {"red", "green", "blue"}
try:
print(colors[0])
except TypeError as error:
print("TypeError:", error)Output:
TypeError: object of type 'generator' has no len()
TypeError: 'set' object is not subscriptableA generator has no length, because it produces values on demand. A set has a length, but it has no positions, so colors[0] is meaningless. File objects, map results, dict.items() views, and many library iterators are in the same position. A for loop over the object itself works for all of them. An index loop works for none of them. If you write index loops by habit, you will have to rewrite the code the day the input changes from a list to something lazier.
Indexing is not free on every container
For a list, items[i] is a constant-time operation. For other sequence types it can be much slower. In a collections.deque, indexing near the middle takes time proportional to the length. A loop that indexes every position then becomes quadratic. Iterating directly visits each element once, whatever the container.
from collections import deque
queue = deque(["a", "b", "c", "d"])
# Each queue[i] may have to walk through the deque
for i in range(len(queue)):
print(queue[i])
# One pass, no repeated lookups
for item in queue:
print(item)For four items the difference does not matter. For millions it does, and the direct loop is also the shorter one.
Parallel lists drift apart
Index loops are often used to walk two lists together:
names = ["Ada", "Grace", "Linus"]
scores = [95, 88]
for i in range(len(names)):
print(names[i], scores[i])This prints Ada 95 and Grace 88, then raises IndexError on the third pass because scores has only two items. Now swap the bound:
for i in range(len(scores)):
print(names[i], scores[i])This version runs without error and prints only two lines. Linus is dropped without any warning. Which list you put inside len() decides whether you get a crash or silent data loss. Nothing in the code states which behavior you intended. Chapter 7 covers how zip makes this choice explicit.
Mutating the list while indexing
range(len(nums)) is computed once, before the loop starts. If the loop body shrinks the list, the range still promises indices that no longer exist.
nums = [1, 2, 3, 4]
try:
for i in range(len(nums)):
if nums[i] % 2 == 0:
del nums[i]
except IndexError as error:
print("IndexError:", error)
print(nums)Trace it. At i = 1 the value 2 is deleted and the list becomes [1, 3, 4]. At i = 2 the value is now 4, which is also deleted, giving [1, 3]. At i = 3 the lookup fails. The loop crashes, and even the part that ran skipped 3 after the first deletion because the items shifted left. The stable fix is to build a new list, for example [n for n in nums if n % 2 != 0]. The point here is that an index loop makes this class of bug easy to write because the loop keeps counting positions that have moved.
The loop variable leaks
After a for loop ends, its variable stays defined in the enclosing scope. With an index loop this has an extra twist:
items = []
for i in range(len(items)):
print(items[i])
try:
print("last index:", i)
except NameError as error:
print("NameError:", error)With an empty list the body never runs, so i is never assigned and the later use fails with NameError. With a non-empty list the same later line would work, so the bug only appears on empty input. Code that depends on a loop variable after the loop is fragile with any loop style, but index loops invite it because i feels like a useful result.
Manual counters
The second pattern avoids range(len(...)) by looping over the items and keeping a separate counter.
fruits = ["apple", "banana", "cherry"]
i = 0
for fruit in fruits:
print(i, fruit)
i += 1This fixes the problems with non-sequences, because the loop iterates the object directly. It does not fix the bookkeeping. You now own three things: the initial value, the increment, and the placement of the increment. Each can go wrong.
Forgetting the increment
If i += 1 is missing, every line prints 0. Nothing crashes and the output looks plausible until someone reads it carefully.
Resetting in the wrong place
Initializing the counter inside the loop, rather than before it, resets the counter on every pass:
for fruit in fruits:
i = 0
print(i, fruit)
i += 1Every line prints 0. The increment executes, but the next pass resets it immediately.
continue skips the increment
This is the most common real bug. Suppose you want to print each non-blank, non-comment line with its line number, and you put the increment at the bottom of the loop:
lines = ["# comment", "alpha", "", "beta"]
line_number = 1
for line in lines:
if not line or line.startswith("#"):
continue
print(line_number, line)
line_number += 1Output:
1 alpha
2 betaThe real line numbers are 2 and 4. The counter counts lines that were printed, not lines that were read, because continue jumps over line_number += 1. The code does what it says, but not what you meant. Moving the increment to the top of the loop fixes this, and then every later edit has to keep that increment above every continue.
The flowchart below shows the path that causes the bug. A skipped line returns to the loop test without passing through the increment.
Starting value confusion
When the counter is meant for people, you usually want it to start at 1. Then you must remember to write line_number = 1 and, if you later reuse the loop for something zero-based, change it again. If you use range(len(...)) you end up with i + 1 scattered through the body, and sooner or later one use is missing the + 1.
tasks = ["write", "test", "ship"]
for i in range(len(tasks)):
print(f"{i + 1}. {tasks[i]}")This is correct, but it combines both problems: index lookup and offset arithmetic.
Summary of the failure modes
| Pattern | Typical failure | Visible symptom |
|---|---|---|
| `range(len(seq) + 1)` | Bound too large | `IndexError` |
| `range(1, len(seq))` | Bound too small | Silently skips the first item |
| `range(len(x))` on a generator | No `len()` | `TypeError` |
| `x[i]` on a set | No positions | `TypeError` |
| Two lists indexed by one `i` | Lengths differ | `IndexError` or silent data loss |
| `del` inside an index loop | Range is stale | `IndexError` and skipped items |
| Manual counter, no increment | Forgotten line | Every number is the same |
| Manual counter, increment after `continue` | Increment skipped | Numbers do not match positions |
When an index is the right tool
Index-based loops are not wrong in every case. There are real situations where you need positions as positions.
Assigning back into the list by position is one:
prices = [10.0, 20.0, 30.0]
for i in range(len(prices)):
prices[i] = prices[i] * 1.1
print(prices)Here prices[i] = ... needs i. Rebinding a loop variable such as price would not change the list. A list comprehension that builds a new list is often better. If you need to update in place, you need the index, and the next chapter shows that enumerate gives it to you without range(len(...)).
Looking at neighbors is another:
readings = [3, 5, 4, 9]
for i in range(len(readings) - 1):
print(readings[i + 1] - readings[i])This prints 2, -1, 5. The loop needs access to the item after the current one, which a plain for over values cannot give you. The - 1 in the bound is deliberate and is the kind of arithmetic that deserves a comment.
Stepping through positions in an unusual order is a third. Examples are range(0, len(seq), 2) for every other item, or counting backward with range(len(seq) - 1, -1, -1). Slicing or reversed() often covers these cases more clearly, but when the algorithm is truly about positions, an index loop is honest.
What the better versions look like
You do not need the details yet, because the next chapters introduce them. Here is a preview so the problems above have an answer in mind.
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(index, fruit)lines = ["# comment", "alpha", "", "beta"]
for line_number, line in enumerate(lines, start=1):
if not line or line.startswith("#"):
continue
print(line_number, line)The second example prints 2 alpha and 4 beta, which are the true line numbers. The counter is advanced by the loop itself, so continue cannot skip it. There is no initial value to forget, no increment to misplace, and no len() or [i] anywhere. The same loop also works if lines is a generator or an open file.
Common mistakes to watch for
- Treating a missing
IndexErroras proof of correctness. Off-by-one bugs that skip items produce no error. - Using one index to read from two lists without checking their lengths.
- Adding or removing items from the list you are iterating over by index.
- Placing a counter increment after a
continueor an earlybreakpath. - Reading the loop variable after the loop, which fails on empty input.
- Reaching for
range(len(x))on input that might later become a generator, file, or set.
Exercises
Exercise
The loop below is meant to print each non-empty name with its position in the original list, starting from 1. It prints the wrong numbers. Explain why, and say what the output is. names = ["Ada", "", "Grace", "", "Linus"] n = 1 for name in names: if not name: continue print(n, name) n += 1
Show answer
The increment n += 1 sits after continue, so it runs only for names that are printed. The counter therefore counts printed names, not list positions. The output is 1 Ada, 2 Grace, 3 Linus, while the true positions are 1, 3, and 5. Replacing the counter with for n, name in enumerate(names, start=1): fixes it, because the loop advances the number on every pass, including skipped ones.
Exercise
Given a = [10, 20, 30] and b = [1, 2], what does each loop do?
Loop 1: for i in range(len(a)): print(a[i], b[i])
Loop 2: for i in range(len(b)): print(a[i], b[i])
Show answer
Loop 1 prints 10 1 and 20 2, then raises IndexError when i is 2, because b has no third item. Loop 2 prints the same two lines and finishes without error, silently ignoring 30. The two loops differ only in which list is passed to len(), and nothing in the code says which behavior was intended.
Exercise
Why does for i in range(len(x)): print(x[i]) fail when x is a generator, and what is the simplest fix when the body needs only the items?
Show answer
A generator has no length, so len(x) raises TypeError. Even if it had a length, generators do not support indexing. The simplest fix is for item in x: print(item), which works for any iterable. If the body also needs a position number, use for i, item in enumerate(x):.