Iterating Over Lists and Other Sequences
Python's for loop is fundamentally different from C/C++ for loops: it is iterator-based rather than index-based, meaning Python automatically manages the sequence of values instead of requiring you to manage a counter.
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)?
Start: Python creates an iterator from range(0, 5).
First iterations: The iterator supplies 0, then 1, then 2. Each supplied value is assigned to i before the loop body runs.
Final 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.
Identify the counter range: The C or C++ condition i < 5, starting from 0 and increasing by 1, produces the values 0 through 4.
Use range: Python expresses those values with range(0, 5).
Write 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 |
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
Treating the Python loop variable as a manually managed index.
The iterator supplies the current value from the sequence, not a counter that you increment yourself.
Fix:
Use the loop variable as the current element unless the task specifically requires a position.Manually adding initialization, a stopping condition, or an increment to a Python for loop.
Python's iterator-based loop already obtains values and stops when the iterator has no more values.
Fix:
Name the loop variable and the iterable directly, such as for item in items:.Assuming every Python for loop must use an index.
Python can iterate directly over lists and other sequences without knowing their length or managing positions.
Fix:
Iterate over the sequence itself when the body needs the elements.Forgetting that index-based loops can create management bugs.
Such mistakes can produce off-by-one errors or infinite loops.
Fix:
Prefer 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
- Python's for loop is iterator-based: it receives values from a sequence one at a time.
- A traditional C or C++ for loop is index-based and requires manual initialization, condition checking, and incrementing.
- for i in range(0, 5) produces 0, 1, 2, 3, and 4 without manually managing a counter.
- Python's loop is similar in behavior to C# foreach and Java enhanced-for loops.
- Direct iteration reduces opportunities for off-by-one errors, infinite loops, and forgotten increments.
Key Takeaways
- 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.