Sub topic 7
Looping by Index with range(len(...))
This chapter covers the for i in range(len(seq)) pattern: what it does, the few cases where it is the right tool, and the mistakes it invites. It assumes you can write a basic for loop, you know that range(start, stop, step) excludes stop, and you can index and slice lists and strings.
What the pattern does
A for loop over a list gives you the items. Sometimes you need the positions instead. len(seq) returns the number of items, and range(len(seq)) produces the integers 0 up to, but not including, that number. These are exactly the valid indexes of the sequence.
colors = ["red", "green", "blue"]
print(len(colors)) # 3
print(list(range(len(colors)))) # [0, 1, 2]
for i in range(len(colors)):
print(i, colors[i])This prints 0 red, 1 green, and 2 blue. The loop variable i is an integer, and you fetch each item yourself with colors[i].
The pattern works for any object that has a length and supports indexing: lists, tuples, strings, and ranges. It does not work for sets or dictionaries, which cannot be indexed by position. It also fails for generators, which have no len().
Why it is usually not the first choice
For plain traversal, the index adds noise. Compare these two loops:
names = ["Ada", "Grace", "Linus"]
for i in range(len(names)):
print(names[i])
for name in names:
print(name)The second loop is shorter, and it cannot raise IndexError. It also works on any iterable, so you can later change names to a set or a generator without touching the loop. Use range(len(...)) only when you need something the plain loop cannot give you.
When an index is the right tool
Writing back into the list
Assigning to the loop variable in a for item in seq loop rebinds a local name. It does not change the list. Assigning through an index does change it.
nums = [1, 2, 3, 4]
for n in nums:
n = n * n
print(nums) # [1, 2, 3, 4]: unchanged
for i in range(len(nums)):
nums[i] = nums[i] * nums[i]
print(nums) # [1, 4, 9, 16]In the first loop, n is a separate name that points at each item in turn, so n = n * n only moves that name. In the second loop, nums[i] = ... replaces the item stored in the list.
enumerate() can do the same job with less indexing: for i, n in enumerate(nums): nums[i] = n * n. A list comprehension is better still when you can build a new list instead of changing the old one.
Looking at neighbors
When each step needs the current item and the next one, you need positions. Stop one early so that i + 1 stays in bounds.
temps = [18, 21, 19, 25]
for i in range(len(temps) - 1):
change = temps[i + 1] - temps[i]
print(f"{temps[i]} -> {temps[i + 1]}: {change:+d}")The output is:
18 -> 21: +3
21 -> 19: -2
19 -> 25: +6There are four items but only three adjacent pairs, so the loop runs three times. If temps is empty, len(temps) - 1 is -1. range(-1) is empty, so the loop body never runs and no error occurs. An equivalent form is zip(temps, temps[1:]), which avoids the arithmetic but copies the slice.
Walking backwards by position
To visit indexes from last to first, count down with a negative step. The stop value is -1 because range excludes it, and 0 must be included.
word = "stop"
for i in range(len(word) - 1, -1, -1):
print(i, word[i])This prints 3 p, 2 o, 1 t, and 0 s. The same indexes are easier to read as reversed(range(len(word))). If you only need the items in reverse order, use for ch in reversed(word).
Choosing positions yourself
An index loop also fits when you want a pattern that is not "every item once":
- Every second item:
range(0, len(seq), 2). - Items in the second half:
range(len(seq) // 2, len(seq)). - Comparing item
iwith itemlen(seq) - 1 - i, as in a palindrome check.
def is_palindrome(text):
for i in range(len(text) // 2):
if text[i] != text[len(text) - 1 - i]:
return False
return True
print(is_palindrome("level")) # True
print(is_palindrome("python")) # FalseOnly half the string is checked, because each comparison covers two positions. For "level", len(text) // 2 is 2, so the middle letter is never compared with itself.
Choosing between loop styles
The last branch is the narrow one: neighbors, computed positions, or writes that do not fit the other tools.
Common errors
Off-by-one bounds
Most index-loop bugs come from the bounds passed to range. The table shows the usual cases for a list xs with at least two items.
| You wrote | What happens |
|---|---|
| `range(len(xs))` | Visits every valid index. Correct for full traversal. |
| `range(len(xs) + 1)` | The last index is `len(xs)`, so `xs[i]` raises `IndexError`. |
| `range(1, len(xs))` | Skips index `0`. Correct only if you intend to skip the first item. |
| `range(len(xs) - 1)` | Skips the last index. Correct for neighbor pairs, wrong for full traversal. |
| `range(len(xs), 0, -1)` | Starts at `len(xs)`, which is out of range, and never reaches `0`. |
Fix the last row by starting at len(xs) - 1 and stopping at -1, as in the backwards example above.
The range is fixed when the loop starts
range(len(items)) is evaluated once, before the first iteration. If the loop body changes the length of the list, the range does not adjust.
items = ["a", "b", "c"]
for i in range(len(items)):
if items[i] == "b":
items.append("x")
print(items) # ['a', 'b', 'c', 'x']: the new item is never visited
items = ["a", "b", "c"]
try:
for i in range(len(items)):
if items[i] == "a":
items.pop(0)
except IndexError:
print("IndexError: the list shrank under the loop")The first loop silently ignores the appended item. In the second loop, removing an item shifts the rest left, so index 2 no longer exists when the loop reaches it. Both behaviors are reasons to avoid changing a list's length inside an index loop. Build a new list, or loop over a copy.
Using the index when you do not need it
If the body only ever writes seq[i] and never uses i alone, the loop should be for item in seq. A rule of thumb: if i appears only inside seq[i], rewrite the loop.
Indexing two sequences of different lengths
This pattern assumes a and b have the same length:
a = [1, 2, 3]
b = [10, 20]
for i in range(len(a)):
print(a[i] + b[i]) # IndexError on the third passzip(a, b) stops at the shorter input and avoids the crash, though it can hide a length mismatch. On Python 3.10 and later, zip(a, b, strict=True) raises ValueError if the lengths differ. Use that when a mismatch means a bug.
Summary of the working model
range(len(seq))yields the indexes0tolen(seq) - 1, computed once when the loop starts.- Use it for writes by position, neighbor comparisons, reversed indexes, and custom stepping.
- For plain traversal, prefer
for item in seq. For index plus value, preferenumerate(). For parallel sequences, preferzip(). - Check the bounds first. Most bugs here are one position too many or too few.
Exercise
A list scores = [70, 75, 73, 80] is given. Using range and indexing, write a loop that counts how many times a score is higher than the one before it. What should the loop use as its range, and what is the final count?
Show answer
Compare each score with the previous one, so loop over range(1, len(scores)) and test scores[i] > scores[i - 1]. Starting at 1 keeps i - 1 from becoming -1. The comparisons are 75 > 70 (yes), 73 > 75 (no), and 80 > 73 (yes), so the count is 2. An equivalent bound is range(len(scores) - 1) with the test scores[i + 1] > scores[i].
Exercise
What does list(range(len("abc") - 1, -1, -1)) return, and why is the stop value -1 instead of 0?
Show answer
It returns [2, 1, 0]. The string has length 3, so the start is 2. range excludes its stop value, so a stop of 0 would end the count at 1 and skip index 0. Stopping at -1 includes 0 as the last value.