The iterator protocol lets you go through items one by one in a simple way. It helps you work with collections like lists or custom objects easily.
Iterator protocol in Python
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Python
class MyIterator: def __iter__(self): return self def __next__(self): # return next item or raise StopIteration pass
The __iter__ method returns the iterator object itself.
The __next__ method returns the next item or raises StopIteration when done.
Examples
iter() to get an iterator from a list and next() to get items one by one.Python
my_list = [1, 2, 3] my_iter = iter(my_list) print(next(my_iter)) # prints 1 print(next(my_iter)) # prints 2
Python
class CountDown: def __init__(self, start): self.current = start def __iter__(self): return self def __next__(self): if self.current < 1: raise StopIteration val = self.current self.current -= 1 return val for num in CountDown(3): print(num)
Sample Program
This program creates a simple iterator over a list of fruits. It prints each fruit one by one.
Python
class SimpleIterator: def __init__(self, data): self.data = data self.index = 0 def __iter__(self): return self def __next__(self): if self.index >= len(self.data): raise StopIteration item = self.data[self.index] self.index += 1 return item items = ['apple', 'banana', 'cherry'] for fruit in SimpleIterator(items): print(fruit)
Important Notes
Always raise StopIteration in __next__ when no more items are left.
The for loop automatically calls iter() and next() behind the scenes.
Summary
The iterator protocol uses __iter__ and __next__ methods to loop over items.
It helps process items one at a time, saving memory and making code cleaner.
You can use it with built-in collections or create your own custom iterators.
Practice
1. What does the
__iter__ method do in the iterator protocol?easy
Solution
Step 1: Understand the role of
The__iter____iter__method is called to get an iterator object from an iterable.Step 2: Identify what
It returns the iterator object itself, which has the__iter__returns__next__method to fetch items.Final Answer:
Returns the iterator object itself -> Option AQuick Check:
__iter__returns iterator object [OK]
Hint: Remember: __iter__ returns the iterator itself [OK]
Common Mistakes:
- Confusing __iter__ with __next__
- Thinking __iter__ returns the next item
- Assuming __iter__ stops iteration
2. Which of the following is the correct way to define an iterator class in Python?
easy
Solution
Step 1: Check required methods for iterator
An iterator class must have__iter__returning self and__next__to get next item.Step 2: Match methods with options
class MyIter: def __iter__(self): return self def __next__(self): pass correctly defines both__iter__and__next__methods.Final Answer:
Defines both __iter__ and __next__ methods -> Option CQuick Check:
Iterator class needs __iter__ and __next__ [OK]
Hint: Iterator class must have __iter__ and __next__ methods [OK]
Common Mistakes:
- Using next() instead of __next__()
- Missing __iter__ method
- Defining iter() instead of __iter__()
3. What will be the output of this code?
class Count:
def __init__(self, limit):
self.limit = limit
self.num = 0
def __iter__(self):
return self
def __next__(self):
if self.num < self.limit:
self.num += 1
return self.num
else:
raise StopIteration
for i in Count(3):
print(i, end=' ')medium
Solution
Step 1: Understand the iterator behavior
The Count class starts num at 0 and returns num+1 until it reaches limit 3.Step 2: Trace the loop output
Loop prints 1, 2, 3 then raises StopIteration to end loop.Final Answer:
1 2 3 -> Option DQuick Check:
Count(3) yields 1 to 3 [OK]
Hint: StopIteration ends loop; count from 1 to limit [OK]
Common Mistakes:
- Starting count from 0 instead of 1
- Expecting 4 as output
- Thinking StopIteration causes error
4. Identify the error in this iterator implementation:
class MyIter:
def __init__(self):
self.data = [1, 2, 3]
self.index = 0
def __iter__(self):
return self
def __next__(self):
if self.index <= len(self.data):
result = self.data[self.index]
self.index += 1
return result
else:
raise StopIterationmedium
Solution
Step 1: Analyze the index condition
Index goes from 0 to len(data)-1. Using <= allows index == len(data), causing IndexError.Step 2: Correct the condition
Change condition toself.index < len(self.data)to avoid out-of-range access.Final Answer:
The condition should be self.index < len(self.data) -> Option AQuick Check:
Index must be less than length to avoid error [OK]
Hint: Use < to avoid index out of range errors [OK]
Common Mistakes:
- Using <= instead of < in index check
- Forgetting to return self in __iter__
- Starting index at 1 instead of 0
5. You want to create a custom iterator that returns only even numbers from 0 up to a given limit (exclusive). Which implementation correctly follows the iterator protocol and filters evens?
class EvenIterator:
def __init__(self, limit):
self.limit = limit
self.current = 0
def __iter__(self):
return self
def __next__(self):
while self.current < self.limit:
val = self.current
self.current += 1
if val % 2 == 0:
return val
raise StopIterationhard
Solution
Step 1: Check iterator protocol methods
Class defines__iter__returning self and__next__with loop and StopIteration.Step 2: Verify filtering logic
Inside__next__, it loops until limit, returns only even values, skipping odds.Final Answer:
Correct implementation returning even numbers up to limit -> Option BQuick Check:
Iterator filters evens correctly [OK]
Hint: Use while loop inside __next__ to skip unwanted items [OK]
Common Mistakes:
- Returning odd numbers by mistake
- Not raising StopIteration when done
- Returning new iterator in __iter__ each time
