Iterators and next in Python
The protocol under every for loop: iter, next, exhaustion.
colors = iter(["red", "green", "blue"])
first = next(colors)
second = next(colors)
rest = list(colors)
done = next(colors, "exhausted")
letters = iter("hi")
pairs = zip([1, 2, 3], "abc")
zipped = list(pairs)
numbered = list(enumerate(["a", "b"], start=1))
How it works
iterturns a list into a one-way stream.nextpulls items; a default avoids StopIteration.zipandenumeratebuild richer iterators.
Keywords and builtins used here
enumerateiterlistnextzip
The run, in numbers
- Lines
- 12
- Characters to type
- 258
- Tokens
- 97
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 61 seconds.
Step 1 of 7 in Iterators, errors & files, step 44 of 72 in Language basics.