Skip to content
BIASED

Lists and tuples

A list as a dynamic array of references, why append costs O(1) on average and an insert at the front O(n), what a copy copies, when to use a deque or a tuple, and how stable sorting works.

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.

An array of references

Growing by one slot copies n(n−1)/2n(n-1)/2 items in all, about 5⋅10115 \cdot 10^{11} for a million numbers. A list avoids this with two ideas.

First, a list stores references, not objects. As the topic Values, types and names showed, a name refers to an object; a list slot does the same. In CPython a list object holds its length, its capacity (the number of slots it has room for) and a pointer to a separate array of slots. A slot is a pointer, 8 bytes on a 64-bit machine, whatever it refers to. sys.getsizeof reports the list object with its slot array, and nothing the slots refer to:

import sys
 
print(sys.getsizeof([]))
xs = []
for v in (10, 20, 30, 40, 50):
    xs.append(v)
    print(len(xs), sys.getsizeof(xs))
print(sys.getsizeof([10**100] * 3) == sys.getsizeof([0] * 3))
56
1 88
2 88
3 88
4 88
5 120
True

Second, a list over-allocates. The empty list's 56 bytes are all header. The first append adds 32 bytes, four slots, although the list holds one item. Appends 2 to 4 cost no memory, and the fifth adds 32 bytes more. The last line shows that the size of the items does not matter: a 101-digit integer and a 0 each take one 8-byte slot. All byte counts in this topic are those of CPython 3.14 on a 64-bit machine; other versions and builds may differ.

At the fifth append the array is full: the length equals the capacity. CPython allocates a larger array, copies the four references into it and then writes the reference to 50 into the first free slot. The int objects themselves never move. Reading xs[4] is one address computation, the start of the array plus 4⋅84 \cdot 8 bytes, so indexing costs O(1)O(1) at any length.

Why append is cheap on average

How much larger is the new array? When one append needs room for nn items, list_resize in CPython's Objects/listobject.c chooses

new capacity=(n+⌊n/8⌋+6) rounded down to a multiple of 4.\text{new capacity} = \big(n + \lfloor n/8 \rfloor + 6\big) \text{ rounded down to a multiple of } 4.

Reading the capacity as (sys.getsizeof(xs) - 56) // 8 after each append gives exactly the numbers of this rule:

import sys
 
EMPTY = sys.getsizeof([])
xs, caps = [], [0]
for i in range(100):
    xs.append(i)
    cap = (sys.getsizeof(xs) - EMPTY) // 8
    if cap != caps[-1]:
        caps.append(cap)
print(caps)
[0, 4, 8, 16, 24, 32, 40, 52, 64, 76, 92, 108]

Each capacity is more than 9/89/8 of the previous one, and this constant factor is what makes appending cheap. Count the references copied by resizes during nn appends. The last resize, at capacity cK<nc_K < n, copies at most cKc_K references. The one before copied at most 89cK\tfrac89 c_K, the one before that (89)2cK(\tfrac89)^2 c_K, and so on. The geometric series sums to

cK(1+89+(89)2+…)=cK1−8/9=9 cK<9n.c_K\Big(1 + \tfrac89 + \big(\tfrac89\big)^2 + \dots\Big) = \frac{c_K}{1 - 8/9} = 9\,c_K < 9n.

Each append also writes its own reference, so nn appends cost fewer than 10n10n reference writes. This is amortized O(1)O(1): one append is occasionally expensive, but nn appends cost O(n)O(n) in total. Counted exactly, as if every resize moved the array, a million appends copy 8,445,096 references, 8.45 per append. CPython traded a little copying for memory: right after a resize, at most about one slot in nine is empty.

The mistake. xs = xs + [v] in a loop throws all this away. + builds a new list each time and copies every reference into it, which is the grow-by-one baseline again. xs.append(v) and xs += [v] extend the list in place.

Indexing and slicing

Indexing and slicing work as for strings in Strings and text; now we can say what they cost. For a list of length nn, xs[i] with 0≤i<n0 \le i < n is the item at position ii, and a negative index counts from the end: xs[-1] is xs[n - 1]. Any other index raises IndexError. A slice xs[start:stop:step] builds a new list from the positions start, start + step, … that come before stop. Omitted bounds mean "from the start" and "to the end", and bounds past the end are clipped, not reported.

losses = [0.9, 0.7, 0.6, 0.55, 0.52]
print(losses[0], losses[-1])
print(losses[1:4])
print(losses[::2])
print(losses[::-1])
print(losses[3:100])
losses[1:3] = [0.65]
print(losses)
0.9 0.52
[0.7, 0.6, 0.55]
[0.9, 0.6, 0.52]
[0.52, 0.55, 0.6, 0.7, 0.9]
[0.55, 0.52]
[0.9, 0.65, 0.55, 0.52]

The stop position is excluded, so xs[:k] and xs[k:] split a list with no item lost or repeated. Indexing costs O(1)O(1). A slice of kk items costs O(k)O(k), because it builds a new list and copies kk references into it.

Unlike a string, a list accepts assignment to a slice. The positions of the slice are replaced by the items on the right, and the list may grow or shrink. Above, two items became one, and the items after them moved left.

Shallow and deep copies

Assignment copies nothing (Values, types and names): after b = a, both names refer to one list. When you do want a copy, there are two kinds.

A shallow copy, xs.copy(), list(xs), xs[:] or copy.copy(xs), is a new list whose slots hold the same references as the original: a new container, the same elements. A deep copy, copy.deepcopy(xs), copies the container and, recursively, every mutable object inside it.

import copy
 
rows = [[1, 2], [3, 4]]
shallow = rows.copy()
deep = copy.deepcopy(rows)
print(shallow is rows, shallow[0] is rows[0], deep[0] is rows[0])
rows[0].append(99)
print(shallow)
print(deep)
False True False
[[1, 2, 99], [3, 4]]
[[1, 2], [3, 4]]

The shallow copy is a different list, but its first slot refers to the same inner list as rows[0]. A change made through rows therefore shows in shallow. Rebinding a slot is another matter: rows[1] = [7] changes which object a slot of rows refers to and leaves shallow alone. For a list of numbers or strings, which are immutable, a shallow copy is as good as a deep one.

The operator * repeats references in the same way. [0] * 3 repeats a reference to the immutable 0, which is harmless. [[0] * 3] * 3 repeats a reference to one mutable row three times:

grid = [[0] * 3] * 3
grid[0][0] = 1
print(grid, grid[0] is grid[1])
grid = []
for _ in range(3):
    grid.append([0] * 3)
grid[0][0] = 1
print(grid)
[[1, 0, 0], [1, 0, 0], [1, 0, 0]] True
[[1, 0, 0], [0, 0, 0], [0, 0, 0]]

The symptom is a change made in one place that appears in several. Test the suspects with is, and create each inner object separately, as the loop does.

The front of a list and deque

The slots of a list are contiguous and in order. An insertion or deletion at position ii must therefore move every slot after ii. xs.insert(i, x), del xs[i] and xs.pop(i) cost O(n−i)O(n - i): O(n)O(n) at the front, O(1)O(1) at the end. x in xs, xs.index(x) and xs.remove(x) compare with the items one by one and cost O(n)O(n) too.

The difference is large. On one laptop with n=106n = 10^6, an insert(0, x) or pop(0) took about 170 microseconds, and an append or pop() at the end about 13 nanoseconds. The exact timings depend on the machine; the front growing in proportion to nn while the end stays flat does not.

When items are added or removed at both ends, as in a queue, use collections.deque, a double-ended queue. CPython builds it as a doubly linked list of blocks of 64 references. Adding at either end writes into the end block or links a new one, and nothing moves. append, appendleft, pop and popleft cost O(1)O(1). The price is indexing: d[i] in the middle walks the blocks and costs O(n)O(n).

With maxlen, a deque keeps only the most recent items and discards from the other end. That is a running average of the last three losses:

from collections import deque
 
recent = deque(maxlen=3)
for loss in [0.9, 0.7, 0.6, 0.55, 0.52]:
    recent.append(loss)
    print(list(recent), round(sum(recent) / len(recent), 3))
[0.9] 0.9
[0.9, 0.7] 0.8
[0.9, 0.7, 0.6] 0.733
[0.7, 0.6, 0.55] 0.617
[0.6, 0.55, 0.52] 0.557

Tuples as records

A tuple is an immutable sequence. It is indexed and sliced like a list, but once created it cannot gain, lose or replace an item. The comma makes a tuple, not the parentheses: 3, 4 is a tuple, (1) is the integer 1, and a one-item tuple needs a trailing comma, (1,).

import sys
 
point = 3, 4
print(point, (1), (1,))
print(sys.getsizeof((1, 2, 3)), sys.getsizeof([1, 2, 3]))
print({(0, 1): "edge"}[(0, 1)])
point[0] = 5
(3, 4) 1 (1,)
72 88
edge
Traceback (most recent call last):
  ...
TypeError: 'tuple' object does not support item assignment

Its length never changes, so a tuple stores its references inside the object itself, with no separate array and no spare slots. Its contents never change, so a tuple of hashable items is itself hashable: it can be a dictionary key, as (0, 1) is above, and a list cannot. Immutability is shallow, though. A tuple that holds a list cannot swap that list for another, but the list itself can change, and such a tuple is not hashable.

A comma-separated expression packs values into a tuple. A comma-separated target unpacks any iterable into names, position by position, and a starred name collects the rest into a list:

mean, std = 2.5, 1.118
first, *rest = [0.9, 0.7, 0.6]
print(mean, first, rest)
a, b = 1, 2
a, b = b, a
print(a, b)
x, y = (1, 2, 3)
2.5 0.9 [0.7, 0.6]
2 1
Traceback (most recent call last):
  ...
ValueError: too many values to unpack (expected 2, got 3)

The swap needs no temporary name: the right side is evaluated completely before any name is rebound. return mean, std from a function returns one tuple, which the caller unpacks.

A tuple of fixed length whose positions mean something is a record. collections.namedtuple names the positions and is still a tuple:

from collections import namedtuple
 
Example = namedtuple("Example", ["features", "label"])
ex = Example((0.2, 0.8), 1)
print(ex.label, ex[0], ex._replace(label=0))
1 (0.2, 0.8) Example(features=(0.2, 0.8), label=0)

_replace returns a new record, the usual way to "change" an immutable object. The ML courses are full of tuples: the shape of an array, x.shape, is a tuple such as (64, 3, 32, 32), and a dataset returns each example as an (input, label) pair.

Stable sorting

sorted(iterable) returns a new sorted list and leaves its argument alone. xs.sort() sorts the list in place and returns None. Both accept reverse=True and key, a function called once per item whose results are compared instead of the items. lambda r: r[1] is a one-line function without a name that returns r[1]. Both sorts are stable: items with equal keys keep their original order.

words = ["pear", "fig", "apple", "kiwi", "banana"]
print(sorted(words, key=len))
scores = [("cid", 90), ("bob", 85), ("ann", 90), ("dan", 85)]
print(sorted(scores, key=lambda r: r[1], reverse=True))
print(sorted(scores, key=lambda r: (-r[1], r[0])))
print(words.sort(), words)
['fig', 'pear', 'kiwi', 'apple', 'banana']
[('cid', 90), ('ann', 90), ('bob', 85), ('dan', 85)]
[('ann', 90), ('cid', 90), ('bob', 85), ('dan', 85)]
None ['apple', 'banana', 'fig', 'kiwi', 'pear']

By length, 'pear' stays before 'kiwi', and by score, 'cid' stays before 'ann': equal keys, input order. The third line sorts by a tuple key. Tuples compare position by position, so it orders by score descending and breaks ties by name. The last line shows the classic mistake: xs = xs.sort() binds xs to None.

CPython sorts with Timsort. It finds runs, stretches that are already in order, and merges them; since Python 3.11 the merge order follows the powersort policy. The worst case is O(nlog⁡n)O(n \log n) comparisons, and a list that is already sorted takes n−1n - 1. Counting comparisons on 1000 items: 999 when sorted, 8667 in random order, against the lower bound log⁡2(1000!)≈8529\log_2(1000!) \approx 8529 for any comparison sort.

Every lookup in this topic was by position. Finding by value, x in xs, compares items one by one, O(n)O(n). A program that asks "have I seen this word?" for every word of a corpus would spend its time searching. The next topic, Dictionaries and sets, builds the hash table behind dict and set: it finds an item by its value in O(1)O(1) on average, and it needs keys that never change, which is why a tuple can be a key and a list cannot.

Check your understanding

The same questions as in Pulse. Answers are shared between modes.

Full notes

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