Skip to content
BIASED

Lists and tuples

Block 1 of 8~2 min

A sequence that grows

The topic Strings and text treated a string as a sequence that never changes: name[0] = "L" raises TypeError. A training run needs a sequence that does change. One loss arrives per epoch, and the program has to keep them all. Python's answer is the list, and its fixed-size relative, the tuple.

losses = []
for epoch in range(4):
    losses.append(round(1.0 / (epoch + 1), 3))
print(losses)
losses[0] = 0.9
print(losses, len(losses))
[1.0, 0.5, 0.333, 0.25]
[0.9, 0.5, 0.333, 0.25] 4

This topic opens the module on data structures, and its question is what each operation costs. We count simple steps as a function of the length nn. A cost of O(1)O(1) does not grow with nn. A cost of O(n)O(n) grows in proportion to nn: twice the items, about twice the work.

The simplest way to store a sequence is a block of memory with room for a fixed number of items. Item ii sits at a known offset from the start, so reading it is one address computation. The trouble is the size. A full block cannot take another item, so the program must allocate a larger block and copy every item over.

Suppose the block grows by exactly one slot each time. Then adding the kk-th item copies the k−1k - 1 items already stored.

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