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. Calling list() on one would never finish, but next() happily grabs just one item at a time.

Assignment

  1. Write first_item(iterable, default=None) that returns the first item of any iterable, or default if it is empty.
  2. Write take(n, iterable) that returns a list of the first n items (or fewer, if the iterable runs out). It must work on endless iterators, so don't turn the whole thing into a list first!