Reading — step 1 of 8
Learn
Repetition is what makes computers powerful. A human gets bored adding a thousand numbers; a computer does it in microseconds without complaint. The for loop is Python's workhorse for repetition — you reach for it when you know what you're iterating over: a range of numbers, the characters in a string, the items in a list.
The shape of a for loop
The header reads as: "For each i IN range(1, 6), run the indented body." Python repeatedly assigns each value from the iterable to the loop variable and runs the body.
Four pieces:
- The keyword
for. - A loop variable (
ihere, but use whatever name describes the value). - The keyword
infollowed by something iterable. - A colon, and an indented block.
range() — three forms
range() is the most common iterable in Python loops. It generates a sequence of integers without storing them all in memory. It has three forms:
The stop value is exclusive — range(1, 6) goes 1 through 5, NOT through 6. This trips up almost every beginner. The convention matches list slicing and is consistent across Python.
Want 1 through 10? Use range(1, 11). Want 1 through N? Use range(1, N + 1).
Iterating over strings, lists, and other iterables
A for loop works on any iterable, not just range:
Counting with enumerate
A classic mistake is reaching for range(len(...)) to get indices:
enumerate(iterable) yields (index, value) pairs. Use it whenever you need both. To start at 1 instead of 0: enumerate(names, start=1).
Pairing two iterables with zip
Sometimes you need to walk two lists in lockstep:
zip stops at the shortest sequence. For unequal lengths where you want to pad, use itertools.zip_longest.
Accumulating a result
A huge fraction of for-loops are computing one value from many:
The pattern: an accumulator variable initialized BEFORE the loop, updated INSIDE.
Common mistakes
- Off-by-one errors:
range(1, N)gives 1 through N-1, not 1 through N. For 1 through N, userange(1, N + 1). - Modifying a list while iterating it:
for x in items: if x == 0: items.remove(x)skips elements unpredictably. Iterate over a copy:for x in items[:]:or build a new list. - Forgetting
rangefor indices:for i in numbers:gives you the values, not the indices. range(len(x))when you really wantedenumerate(x)— works but verbose.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…