Concept Explanation
When you use a for loop in Python to go through a list, have you ever wondered how it knows which item is next?
The secret is the Iterator Protocol. An Iterable is any object you can loop over (like a List or String), but an Iterator is the actual machine that keeps track of the current position and fetches the "Next" item when requested. You can think of it like a deck of cards: the deck is the iterable, and your hand flipping through the cards one-by-one is the iterator.
Syntax or Core Structure
The Iterator Protocol
To be an iterator, an object must implement two methods:
__iter__(): Returns the iterator object itself.__next__(): Returns the next value in the sequence. If there are no more values, it must raise aStopIterationerror.
# Converting an Iterable (List) to an Iterator
my_list = ["apple", "banana", "cherry"]
my_iterator = iter(my_list)
# Manual Iteration
print(next(my_iterator)) # "apple"
print(next(my_iterator)) # "banana"
print(next(my_iterator)) # "cherry"
# print(next(my_iterator)) # This would crash with StopIteration!
Code Example #1 (Basic)
Creating a custom counter iterator.
class Counter:
def __init__(self, low, high):
self.current = low
self.high = high
def __iter__(self):
return self
def __next__(self):
if self.current > self.high:
raise StopIteration
else:
self.current += 1
return self.current - 1
for num in Counter(1, 5):
print(num) # 1, 2, 3, 4, 5
Code Example #2 (Intermediate)
Iterators are "lazy"—they only calculate the next value when you ask for it. This makes them perfect for processing huge datasets that wouldn't fit in your computer's RAM.
# Simulation of an infinite sequence
class EvenNumbers:
def __init__(self):
self.num = 0
def __iter__(self):
return self
def __next__(self):
val = self.num
self.num += 2
return val
evens = EvenNumbers()
print(next(evens)) # 0
print(next(evens)) # 2
print(next(evens)) # 4
# This can go on forever without using much memory!
Real World Example
Imagine you are a data scientist analyzing a 50GB log file. If you try to open the whole file at once, your computer will crash. But Python files are iterators!
# 📂 Large File Iterator Simulation
# with open("massive_data.txt") as f:
# for line in f:
# process(line)
# This only reads ONE LINE at a time into memory.
Common Mistakes
- Exhausting the Iterator: Once an iterator has reached the end (
StopIteration), it is "spent." You cannot use it again; you have to create a new one. - Forgetting
__iter__(): If you only implement__next__(), theforloop won't be able to use your object because it doesn't know it's an iterator. - Infinite Loops: If you forget to raise
StopIterationin your custom iterator, yourforloops will run forever.
Best Practices
- Use Built-ins First: Most of the time, Python's built-in iterables (lists, dictionaries, ranges) are all you need. only create custom iterators for complex patterns.
- Iterators as Filters: You can chain iterators together to create complex data processing pipelines that stay memory efficient.
Practice Exercises
- The Reverser: Create an iterator class
ReverseIterthat takes a list and returns the items in reverse order. - Powers of Two: Write an iterator that returns the powers of two (
2, 4, 8, 16...) up to a specified limit. - Fibonacci Iterator: Challenge! Create a custom iterator that generates the Fibonacci sequence up to 1,000.