Part 10 / Topic 7 of 11
Iterators
- An iterable is anything you can loop over: list, string, dict, file,
range. - An iterator is the object that actually hands out the items one at a time and remembers where it is.
iter(iterable)gives you an iterator.next(iterator)gives the next item. When there are no more,nextraisesStopIteration.
Think of a book (iterable) and a bookmark (iterator): many readers can use the same book, each with their own bookmark.
queue = ["Asha", "Ravi"]
it = iter(queue)
print(next(it)) # Asha
print(next(it)) # Ravi
# next(it) -> StopIteration
A for loop does exactly this for you: it calls iter() once, then next() until StopIteration.
Writing your own iterator
A class (Part 9) becomes an iterator when it has two special methods:
__iter__(self)returns the iterator (usuallyself).__next__(self)returns the next value, or raisesStopIteration.
Real-world example: a rocket launch countdown.
class Countdown:
def __init__(self, start):
self.current = start
def __iter__(self):
return self
def __next__(self):
if self.current <= 0:
raise StopIteration
value = self.current
self.current -= 1
return value
for n in Countdown(3):
print(n, end=" ") # 3 2 1
print()
๐ Going deeper: an iterator is used up after one pass. A list is not an iterator, so
iter(my_list)gives a fresh bookmark each time.
Done here? The practice set for Part 10 โ 8 exercises with solutions โ is on the part page.