python · level 3 · unit 4 · lesson 1
- meet it
- guess first
- your turn
- fix it
- 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).
guess first
One list is shorter. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
names = ["Ana", "Ben", "Cara"]
scores = [91, 78]
for name, score in zip(names, scores):
print(name, score)
print(len(list(zip(names, scores))))
your turn
Your turn. Take a few from an endless supply.
Choose the first ticket number in the first blank, then how many tickets to take in the second.
fix it
Two weeks of sales should join up. Fix it!
- Count the arguments
chainwas handed here. What is that one argument? - It got a single list holding two lists, so it hands out the two lists themselves.
- Pass the lists separately, as
chain(week_one, week_two), then run.
nailed it
you can stitch iterators together. :D
chainjoins several iterables into one stream.countnever ends, so stop it withisliceorzip.zippairs items up and stops at the shortest.
new words in your collection
- itertools
- zip
This lesson isn’t saved. A free account remembers every lesson you finish.