Iterating Over Lists and Other Sequences
In Python, the loop variable normally represents the current value supplied by the sequence, not a position that you must manually increase.
Try it: What a for Loop Hands You
What a Python for loop gives its loop variable from each kind of iterable: the characters of a string, the positions from range(len(word)), the elements of a list, (index, item) pairs from enumerate(), the numbers of range(start, stop, step), a dict's keys, its .values() and its .items() tuples unpacked into key, val, the inner lists of a nested list and the values an inner loop visits; and why removing items from a list while looping over it skips the next item, while looping over a copy nums[:] does not.
How it works
- The for statement asks the object for an iterator, then calls next() on it once per pass.
- Each next() result is bound to the loop variable (a tuple result such as ('a', 10) or (0, 'red') is unpacked into two names), and the indented body runs once with it.
- A string gives characters, a list gives element values (not positions), range() computes start, start + step, … stopping before stop, and a dict gives its keys in insertion order (.values() the values, .items() key-value tuples).
- A nested list's inner list is one element of the outer loop; a second, inner for loop is needed to visit the values inside it.
- A list iterator only remembers a position number into the live list: removing an item shifts the later items left, so the item that slides into the passed position is skipped. Looping over a copy (nums[:]) keeps the positions fixed.
- When next() has nothing left the loop ends (StopIteration) and the loop variable keeps its last value; an empty iterable runs the body zero times.
Default run (10 steps): A 3-line program. Step through it: each pass of the for loop asks the iterator for its next item, binds the loop variable to it and runs the indented body once. … Done: the loop body ran 3 times. Output: red | green | blue.
Simplified: The programs are twelve fixed templates: you choose the loop and edit only its data (a short string, list items that are words or integers, key: value pairs with word keys and integer values, range numbers from -20 to 20, up to 4 rows of integers, up to 10 numbers). Nothing you type is executed: the lab's own small parsers turn it into literals, and a model of CPython's iterator protocol written for these loops runs the program. Every program was also run in CPython 3.12 under sys.settrace, and the lab reproduces the variables before every line, the printed output, the final variables and the error.
Loading the simulation…
A Different Kind of For Loop
If you learned to program with C or C++, the word for may suggest a counter, a condition, and an update operation. Python uses the same keyword for a different mechanism. Its for loop is iterator-based rather than index-based: Python obtains values from a sequence one at a time and assigns each value to the loop variable.
In Python, the loop variable normally represents the current value supplied by the sequence, not a position that you must manually increase.
Values Moving Through the Loop
An iterator is an object that knows how to produce values one at a time and in order. For a Python for loop, Python creates an iterator from the object after in. It repeatedly asks that iterator for the next value, assigns the value to the loop variable, runs the loop body, and then requests another value. When no values remain, the loop stops.
Following Five Values
What values does the loop variable receive in for i in range(0, 5)?
- 1Start
Python creates an iterator from
range(0, 5). - 2First iterations
The iterator supplies 0, then 1, then 2. Each supplied value is assigned to i before the loop body runs.
- 3Final iterations
The iterator supplies 3 and then 4. After those values have been used, there are no more values.
The loop variable receives 0, 1, 2, 3, and 4, one value per iteration.
Counting Versus Iterating
A C or C++ loop such as for (int i = 0; i < 5; i++) makes three responsibilities explicit: initialize the counter, check the condition before each iteration, and increment the counter after each iteration. In Python, for i in range(0, 5) expresses the values to use and leaves those three management tasks to Python.
Translating the Loop
A Direct Translation
Translate a C or C++ loop that repeats five times into Python.
- 1Identify the counter range
The C or C++ condition i < 5, starting from 0 and increasing by 1, produces the values 0 through 4.
- 2Use range
Python expresses those values with
range(0, 5). - 3Write the Python loop
Place the loop body after for i in
range(0, 5):. Python supplies each value and manages the stopping condition and progression.
for i in range(0, 5): is the Python equivalent of the stated C or C++ counting loop.
Lists and Other Iterables
The same iterator-based idea applies beyond a numeric range. Python can iterate over lists, tuples, strings, dictionaries, sets, and custom objects. The loop does not need to know the sequence length or manually manage an index; it requests values from the iterable until no values remain.
red
green
blueHere, item receives each element of the list in order. It is not a counter containing 0, 1, and 2. The loop body runs once with red, once with green, and once with blue. This direct relationship between the loop variable and the current element is what makes the loop useful for many kinds of sequences.
The Foreach Connection
| Language | Loop style | What the loop variable receives |
|---|---|---|
| Python | for item in sequence | The next value from the iterable |
| C# | foreach loop | Each element from the sequence |
| Java | enhanced for loop | Each element from the sequence |
| C or C++ | Index-based for loop | A manually managed counter value |
Python's for loop is closer in behavior to C# foreach and Java enhanced-for than to the traditional C or C++ counting loop.
C# programmers may recognize Python's loop as similar to foreach. Java programmers may recognize it as similar to the enhanced for loop introduced in Java 1.5. In all three styles, the loop works through a sequence and automatically delivers each element to the loop variable, without requiring manual index or counter management.
Mistakes Beginners Make
Common mistake Treating the Python loop variable as a manually managed index.
What it looks likefor item in items: assumes item is a position such as 0 or 1.Why it failsThe iterator supplies the current value from the sequence, not a counter that you increment yourself.
Do this insteadUse the loop variable as the current element unless the task specifically requires a position.
Common mistake Manually adding initialization, a stopping condition, or an increment to a Python for loop.
What it looks likeTrying to reproduce the three control expressions from a C or C++ for statement.
Why it failsPython's iterator-based loop already obtains values and stops when the iterator has no more values.
Do this insteadName the loop variable and the iterable directly, such as for item in items:.
Common mistake Assuming every Python for loop must use an index.
What it looks likeUsing a counter when the loop only needs to process each list element.
Why it failsPython can iterate directly over lists and other sequences without knowing their length or managing positions.
Do this insteadIterate over the sequence itself when the body needs the elements.
Common mistake Forgetting that index-based loops can create management bugs.
What it looks likeA manually controlled loop uses the wrong boundary or fails to advance its counter.
Why it failsSuch mistakes can produce off-by-one errors or infinite loops.
Do this insteadPrefer Python's iterator-based form when direct value iteration expresses the task.
Practice the Translation
Explain how you would translate a C or C++ loop that initializes i to 0, continues while i is less than 5, and increments i after every iteration. Then describe what the Python loop variable receives on each iteration.
Hints
- Identify the values produced by the C or C++ loop.
- Use Python's range form to express those values.
- Remember that Python supplies each value to the loop variable automatically.
A list contains three colors. Describe why a Python loop written as for color in colors: is more direct than a C or C++ loop that manually uses a counter to reach each element.
Hints
- Ask what the loop body actually needs: a position or the color itself.
- Compare direct element delivery with manual counter management.
Key Takeaways
- 1Python's for loop is iterator-based: it receives values from a sequence one at a time.
- 2A traditional C or C++ for loop is index-based and requires manual initialization, condition checking, and incrementing.
- 3for i in
range(0, 5)produces 0, 1, 2, 3, and 4 without manually managing a counter. - 4Python's loop is similar in behavior to C# foreach and Java enhanced-for loops.
- 5Direct iteration reduces opportunities for off-by-one errors, infinite loops, and forgotten increments.
At a glance
- Python for loops obtain values from iterators instead of requiring a manually controlled index.
- The loop variable receives the current element or value supplied by the iterable.
- Traditional C and C++ loops expose counter management; Python hides that control for direct value iteration.
- Python's approach resembles C# foreach and Java enhanced-for loops.
- Removing manual initialization, boundary checks, and increments makes iteration simpler and less error-prone.