typestar

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

  1. iter turns a list into a one-way stream.
  2. next pulls items; a default avoids StopIteration.
  3. zip and enumerate build richer iterators.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 7 in Iterators, errors & files, step 44 of 72 in Language basics.

← Previous Next →