The for Loop & The Iterator Protocol
The for loop is the workhorse of Python data processing. Unlike the while loop, which runs until a condition changes, the for loop is designed for Definite Iteration—it executes once for every item in a collection (an Iterable).
To master the for loop, you must understand the “contract” between the loop and the data it traverses.
1. Basic Iteration
Section titled “1. Basic Iteration”In Python, the for loop doesn’t use a counter (like i++ in C). Instead, it “asks” the collection for its next item.
fruits = ["Apple", "Banana", "Cherry"]
for fruit in fruits: print(f"Current fruit: {fruit}")The “For-In” Logic
Section titled “The “For-In” Logic”- Collection:
fruitsis the iterable. - Variable:
fruitis a temporary label that points to the current object. - Flow: Python automatically stops when there are no items left. No
IndexErroris possible!
2. The Power of range()
Section titled “2. The Power of range()”When you need to iterate a specific number of times, or need an index, Python provides the range() generator.
Anatomy: range(start, stop, step)
Section titled “Anatomy: range(start, stop, step)”range(5)->0, 1, 2, 3, 4(Starts at 0, ends before 5)range(2, 6)->2, 3, 4, 5range(0, 10, 2)->0, 2, 4, 6, 8
# Calculate the sum of numbers 1 to 100total = 0for n in range(1, 101): total += nprint(total) # 50503. Under the Hood: The Iterator Protocol
Section titled “3. Under the Hood: The Iterator Protocol”This is the “secret sauce” of Python. When you write for item in collection:, Python performs a specific dance behind the scenes.
- Get Iterator: Python calls
iter(collection). This returns an Iterator object. - Request Next: The loop calls
next(iterator). - Assign: The returned value is assigned to your loop variable.
- Repeat: This continues until the iterator raises a special error called
StopIteration. - Clean Exit: The
forloop catchesStopIterationand terminates gracefully.
Why this matters
Section titled “Why this matters”This protocol allows for loops to work on anything: lists, strings, files, database cursors, and even infinite streams of data. As long as an object implements __iter__ and __next__, Python can loop over it.
4. Useful Patterns: enumerate and zip
Section titled “4. Useful Patterns: enumerate and zip”enumerate(): Getting the Index
Section titled “enumerate(): Getting the Index”If you need both the item and its position (index), don’t use range(len(list)). Use enumerate.
names = ["Alice", "Bob", "Charlie"]for index, name in enumerate(names): print(f"{index}: {name}")zip(): Iterating in Parallel
Section titled “zip(): Iterating in Parallel”If you have two related lists, zip allows you to traverse them together.
users = ["Alice", "Bob"]ids = [101, 102]
for name, user_id in zip(users, ids): print(f"User {name} has ID {user_id}")5. Summary Table
Section titled “5. Summary Table”| Feature | for Loop | while Loop |
|---|---|---|
| Iteration Type | Definite (fixed number of items) | Indefinite (depends on condition) |
| Mechanism | Iterator Protocol (__next__) | Boolean Evaluation |
| Safety | No risk of infinite loops (usually) | High risk of infinite loops |
| Performance | Faster (optimized in C) | Slower (manual bytecode evaluation) |