Iterator Basics
What is an Iterator?
In Python, an iterator is an object that can be iterated (looped) upon. It represents a stream of data and implements two key methods:
__iter__()
: Returns the iterator object itself
__next__()
: Returns the next value in the iteration sequence
## Simple iterator example
numbers = [1, 2, 3, 4, 5]
my_iterator = iter(numbers)
print(next(my_iterator)) ## 1
print(next(my_iterator)) ## 2
Iterator Protocol
The iterator protocol defines how an object should behave during iteration:
graph LR
A[Iterable Object] --> B[__iter__() method]
B --> C[Iterator Object]
C --> D[__next__() method]
D --> E[Next Value]
D --> F[StopIteration Exception]
Creating Custom Iterators
You can create custom iterators by defining a class with __iter__()
and __next__()
methods:
class CountDown:
def __init__(self, start):
self.count = start
def __iter__(self):
return self
def __next__(self):
if self.count <= 0:
raise StopIteration
self.count -= 1
return self.count + 1
## Using the custom iterator
countdown = CountDown(5)
for num in countdown:
print(num)
Iterator Types in Python
Iterator Type |
Description |
Example |
List Iterator |
Iterates through list elements |
iter([1, 2, 3]) |
Tuple Iterator |
Iterates through tuple elements |
iter((1, 2, 3)) |
Set Iterator |
Iterates through set elements |
iter({1, 2, 3}) |
Dictionary Iterator |
Iterates through dictionary keys |
iter({'a': 1, 'b': 2}) |
Benefits of Iterators
- Memory Efficiency: Load data one item at a time
- Lazy Evaluation: Compute values on-the-fly
- Simplify Looping: Provide clean iteration mechanism
At LabEx, we recommend mastering iterators as a fundamental Python skill for efficient data processing and memory management.