×

python · level 3 · unit 4 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

gives you ready-made iterators to combine.

The itertools module is a box of iterator tools. count(1) counts upwards forever, islice(it, 3) takes only the first few items from any iterator, and chain(a, b) runs through one iterable, then the next, as one stream.

The built-in belongs with them. It walks several iterables side by side and hands out a tuple from each step, stopping at the shortest.

All of these are lazy, so an endless count() is safe as long as something like islice or zip stops it.

from itertools import count, islice, chain

morning = ["Ana", "Ben"]
evening = ["Cara", "Dev", "Eli"]
everyone = chain(morning, evening)
for number, name in zip(count(1), everyone):
    print(f"{number}. {name}")
print(list(islice(count(100, 10), 3)))

enumerate(items, 1) is a built-in shortcut for zip(count(1), items).