
Code
Behind the for Loop
Every for loop secretly uses two tiny functions: iter() and next().
Iterables and iterators
- An iterable is anything you can loop over: lists, strings, dicts, files...
- An iterator is the object that actually walks through it, one item at a time.
iter(thing) asks an iterable for a fresh iterator. next(iterator) hands you
the next item. When nothing is left, next() raises StopIteration.
crates = ["rope", "oil", "map"]
it = iter(crates)
print(next(it)) # rope
print(next(it)) # oil
print(next(it)) # map
next(it) # StopIteration!
A for loop is just this, with the StopIteration caught for you:
it = iter(crates)
while True:
try:
item = next(it)
except StopIteration:
break
print(item)
next() also takes a default that it returns instead of raising:
next(it, "empty").
Pip tip: Some iterators never end, like
itertools.count()which counts 0, 1, 2, 3... forever. Callinglist()on one would never finish, butnext()happily grabs just one item at a time.
Assignment
- Write
first_item(iterable, default=None)that returns the first item of any iterable, ordefaultif it is empty. - Write
take(n, iterable)that returns a list of the firstnitems (or fewer, if the iterable runs out). It must work on endless iterators, so don't turn the whole thing into a list first!
- Write
first_item(iterable, default=None)that returns the first item of any iterable, ordefaultif it is empty. - Write
take(n, iterable)that returns a list of the firstnitems (or fewer, if the iterable runs out). It must work on endless iterators, so don't turn the whole thing into a list first!
main.py Python sleeping
Press Run to try your code, then Check to test it.