Iterators: one item at a time
🌍 In real life. At a bank, a token machine gives out queue numbers. Press the button: token 1. Press again: token 2. The machine remembers where it is, and when the roll of tokens runs out, it can't give any more.
Python has the same idea. A list, a string or a range is an iterable: something you can go through. To actually go through it, Python makes an iterator, a little token machine:
iter(something)makes the iteratornext(it)presses the button: you get the next item- when nothing is left,
nextraises StopIteration
The idea in one sentence: an iterable is something you can go through, and iter() gives you an iterator that hands out its items one at a time with next(), raising StopIteration when there are none left.
Its words:
- iterable: a list, string, range, dict, file: anything a
forloop accepts - iterator: the "token machine" that remembers where it is
next(it): give me the next item- StopIteration: the signal that the iterator is used up
tokens = iter(["A1", "A2", "A3"])
print(next(tokens))
print(next(tokens))
print(next(tokens))
print(next(tokens, "no more tokens"))Why it matters: this is exactly what every for loop does for you, step by step:
for x in items:first callsiter(items)- each round, it calls
next(...)and puts the item inx - when
nextraises StopIteration, the loop stops quietly
An iterator is used up as it goes: once an item is handed out, that iterator won't give it again. A list can be looped over many times, because each for makes a fresh iterator.
queue = ["Ana", "Bo", "Cy"]
it = iter(queue)
print("first:", next(it))
for name in it: # carries on from where next() left off
print("then:", name)
print(list(it)) # used up: nothing left
print(list(queue)) # the list itself is untouchedMistakes and edge cases.
- next() on a list.
next([1, 2])givesTypeError: 'list' object is not an iterator: a list is iterable, but you neediter(list)first. - Going past the end. After the last item,
next(it)raisesStopIteration;next(it, None)givesNoneinstead. - Reusing a used-up iterator. A second loop over the same iterator finds nothing; ask the list for a fresh one with
iter(...)again. - Expecting the list to be used up. Looping over a list twice works fine: each
formakes its own new iterator.
Quiz
What does this print?
it = iter("hey") print(next(it), next(it))What does this print?
it = iter([10, 20, 30]) next(it) print(list(it))What does
next(it)do when the iterator has nothing left?- Raises StopIteration
- Starts again from the first item
- Gives back 0
What does this print?
it = iter([1]) print(next(it, "empty"), next(it, "empty"))Which line has a mistake?
names = ["Ana", "Bo"] first = next(names) print(first)
Coding tasks
Write
first_and_rest(items)that returns a tuple: the first item, and a list of all the others. Useiterandnext.Write
count_left(it)that returns how many items an iterator still has (it may already be partly used).Write
next_token(machine)that gives the next item from the iteratormachine, or the text"sold out"when it has nothing left.