Definition: In Python, an iterator is an object that allows you to traverse a sequence of elements one at a time. Each call to next()
returns the next element, and when there are no more items, it raises a StopIteration
exception.
Iterator vs Iterable
- Iterable: an object that can provide an iterator via
iter()
(e.g.list
,tuple
,set
,dict
). - Iterator: the object returned by
iter()
and consumed bynext()
.
fruits = ["apple", "banana", "cherry"]
# obtain an iterator
it = iter(fruits)
print(next(it)) # apple
print(next(it)) # banana
print(next(it)) # cherry
print(next(it)) # StopIteration (no more elements)
Main Characteristics
- Iterators remember their current position in the sequence.
- They can only be traversed once; once exhausted, a new one must be created.
- They are ideal for large datasets or infinite streams (because they generate elements on demand).
Creating a Custom Iterator
You can define a class implementing the special methods __iter__()
and __next__()
:
class Counter:
def __init__(self, limit):
self.limit = limit
self.count = 0
def __iter__(self):
return self
def __next__(self):
if self.count < self.limit:
self.count += 1
return self.count
else:
raise StopIteration
for num in Counter(3):
print(num)
# 1, 2, 3
Relation with Generators
Generators are a convenient way to create iterators using the yield
keyword:
def count(limit):
for i in range(1, limit + 1):
yield i
for n in count(3):
print(n)
Common Errors and Best Practices
- Iterator exhaustion: once an iterator is consumed, it cannot be reset; use
iter()
again to restart. - StopIteration: signals the end of iteration, not a runtime error.
- Safe iteration:
for
loops automatically handleStopIteration
.
See Also
- Iterable (Python): an object capable of providing an iterator via
iter()
. - Generator (Python): a simpler way to create iterators using
yield
. - Set (
set
): an iterable collection that can be turned into an iterator.