Sub topic 6
How much space common data structures take
This chapter assumes you know Python lists, dictionaries and sets, and that you can read Big O notation. You should also know the difference between input space and auxiliary space. Here you will learn how much memory the common containers need as a function of the number of items they hold.
The basic rule
Most containers use space proportional to the number of items they store. A list of n items is O(n). A dictionary or set with n entries is also O(n), and the constant factor is larger. Hash tables keep spare empty slots so lookups stay fast, so they use several times more memory than a list of the same length.
| Structure | Space for n items | Note |
|---|---|---|
| List or array | O(n) | Stores references to the items |
| Dictionary | O(n) | Stores keys and values, plus spare slots |
| Set | O(n) | Stores keys, plus spare slots |
| String of length n | O(n) | One character per position |
| Binary tree with n nodes | O(n) | Each node holds a value and two links |
| 2D grid, r rows by c columns | O(r · c) | Becomes O(n²) for a square grid |
References and shallow size
A Python list holds references to objects, not the objects themselves. The list's own memory is small, and each item is a separate object elsewhere. sys.getsizeof reports only this shallow size.
import sys
small = [1, 2, 3]
nested = [[0] * 1000 for _ in range(1000)]
print(sys.getsizeof(small))
print(sys.getsizeof(nested)) # counts only the outer list, not the 1,000,000 cellsThe second number is small even though the structure holds a million cells. For Big O analysis, count every element the structure reaches, not only the outer container.
Graph representations
A graph with V vertices and E edges can be stored in two common ways, and the space differs.
def to_adjacency_list(v, edges):
graph = {i: [] for i in range(v)}
for a, b in edges:
graph[a].append(b)
graph[b].append(a)
return graph
def to_adjacency_matrix(v, edges):
matrix = [[0] * v for _ in range(v)]
for a, b in edges:
matrix[a][b] = 1
matrix[b][a] = 1
return matrix
edges = [(0, 1), (1, 2), (2, 3)]
print(to_adjacency_list(4, edges))
print(to_adjacency_matrix(4, edges))The adjacency list stores one entry per vertex and two per undirected edge, so it uses O(V + E) space. The matrix always stores V × V cells, so it uses O(V²) space. For a sparse graph, where E is much smaller than V², the list is far cheaper.
Common errors
- Ignoring the constant factor. A set and a list both use O(n) space, but the set can use several times more bytes. Big O hides this, so measure when memory is tight.
- Counting only the outer container. A list of n lists, each of length m, is O(n · m), not O(n).
- Forgetting nested values. A dictionary mapping each key to a list can hold far more than n items in total. Add up the sizes of all the values.
- Assuming a structure stays the same size. If you append to a list in a loop, its space grows with every iteration, so a loop that appends once per item is O(n) auxiliary space.
Quick way to estimate
- Name the structure you create.
- Ask how many items it holds when the function finishes, or at its peak if items are removed along the way.
- Multiply by the size of each item if the items are themselves containers.
- Keep only the dominant term.
For example, a dictionary of n words, where each word maps to a list of its positions in a text of length n, holds at most n positions in total. The space is O(n), not O(n²).
Exercise
A graph has 1,000 vertices and 3,000 undirected edges. Roughly how many stored entries does an adjacency list need compared with an adjacency matrix, and which has the better Big O space?
Show answer
The adjacency list needs about 1,000 vertex entries plus 2 × 3,000 = 6,000 neighbor entries, so about 7,000 entries, which is O(V + E). The matrix needs 1,000 × 1,000 = 1,000,000 cells, which is O(V²). The adjacency list has the better space here.