Skip to content
BIASED

Iteration, comprehensions and generators

Block 1 of 8~2 min

One loop for many containers

The topic Dictionaries and sets built its word counts with a loop: one for over the words of the corpus, one insertion per pass. The same for has already walked over lists, strings, ranges, the keys of a dict and the members of a set. Yet these objects are laid out very differently. A list is an array of references, and a dict or a set is a hash table with empty slots in it.

A loop over positions shows why that is a puzzle. It needs the object to answer xs[i]:

vocab = {"cat", "mat", "sat"}
i = 0
while i < len(vocab):
    print(vocab[i])
    i += 1

The last line of the traceback says why it fails:

TypeError: 'set' object is not subscriptable

A set has no position 0. A dict has keys instead of positions, so counts[0] looks for the key 0 and raises KeyError: 0, while for w in counts simply walks the keys. The loop over positions also needs a length known in advance, and a stream of sensor readings has none. And it needs every item to exist before the loop starts.

A for loop asks for none of this. This topic opens the small protocol behind it. On top of the protocol it builds two tools: comprehensions, which build collections in one expression, and generators, which compute items only when asked. The running example is the piece of code that feeds a training loop, a data loader that yields batches:

for batch in batches(examples, 32):
    ...  # one gradient step per batch

By the end of the topic batches is written, and it works on data that does not fit in memory.

Answers are saved on the server and tied to this browser until you sign in.