intermediate
Iterators in Python
6 min read
Overview
An Iterator is an object that allows you to traverse through a sequence of data one element at a time. In simple words, an iterator remembers its current position during iteration and returns the next item when asked.
Learning Objectives
- Learn what makes an object iterable vs an iterator.
- Use
iter()to obtain an iterator andnext()to fetch elements. - Create custom iterator classes by implementing
__iter__()and__next__().
Concept Explanation
In Python:
- Iterable: Any object you can loop over using a
forloop (like alist,tuple,str, ordict). An iterable produces an iterator when passed toiter(). - Iterator: An object that implements the iterator protocol with two magic methods:
__iter__(): Returns the iterator object itself.__next__(): Returns the next value in the sequence. When no more items remain, it raises aStopIterationexception.
text
Iterable Object (e.g. [10, 20, 30]) ---> iter() ---> Iterator Object ---> next() ---> 10, 20, 30
Code Examples
Example 1 — Basic Manual Iteration
Using iter() and next() manually to step through a list:
python
numbers = [10, 20, 30]
# Obtain an iterator object from the list
num_iter = iter(numbers)
print(next(num_iter)) # 10
print(next(num_iter)) # 20
print(next(num_iter)) # 30
# Calling next() again raises StopIteration exception
try:
print(next(num_iter))
except StopIteration:
print("Reached the end of the sequence.")
Example 2 — Building a Custom Counter Iterator
Creating a class that acts as a custom iterator:
python
class Counter:
def __init__(self, start, end):
self.current = start
self.end = end
def __iter__(self):
return self
def __next__(self):
if self.current > self.end:
raise StopIteration
val = self.current
self.current += 1
return val
counter = Counter(1, 3)
for num in counter:
print(f"Count: {num}")
Visual Flow
The following execution flow represents step-by-step iterator evaluation:
⚡ Visual Execution Flow
Pass Iterable to iter()→Call next() on Iterator→Yield Current Value & Move Pointer→Raise StopIteration at End
Common Mistakes
- Exhausted Iterators: Trying to loop over an iterator a second time without recreating it. Iterators can only be consumed once.
- Forgetting
return selfin__iter__(): Custom iterators must returnselfinside__iter__().
Best Practices
- Use built-in Python
forloops or generator expressions for simple iterations instead of writing manual__next__()loops.