Inside a list: a row of references
A Python list is one block of references side by side, every slot the same size, so finding slot i takes one multiplication and one addition: a[999999] is as fast as a[0].
In a list of a million numbers, a[999999] is as fast as a[0]: both take one multiplication and one addition. In a linked list, item 999999 means following next 999999 times from the front. The difference is how the items sit in memory: a list is one block of references side by side, every slot the same size, so where slot i is can be worked out directly. The last lesson showed that names and slots hold references; this one shows how those references are laid out inside a list.
A list holds a row of references
a = [10, "hi", [1, 2]] makes one list object. Inside it is a contiguous block of memory split into 3 slots, and each slot holds just one reference (8 bytes on a 64-bit machine) pointing at the real object. The 10, the "hi" and the [1, 2] live elsewhere in memory, and they are all different sizes.
Names
abThe list object: a row of references
[0]ref[1]ref[2]refObjects
1a = [10, "hi", [1, 2]]2b = a[2]3b.append(3)4print(a)5print(a[2] is b)6 7nums = [7] * 38print(nums[0] is nums[2])
[10, 'hi', [1, 2, 3]] True True
[7] * 3 follows the same rule: it copies one reference three times, so all three slots point at the same 7. Integers are immutable, so sharing is harmless.
Why not put the objects straight into the slots? Because objects differ in size: 10 is tiny, a long string may be thousands of bytes. Only when every slot is the same size can one formula say where slot i is. Storing references makes every slot the same size.
A list's slots start at address 2000, and each slot holds an 8-byte reference. Where is the slot for a[1]?
Why a[i] gets there in one step
The slots start at the start address and follow one another, 8 bytes each, so:
address of slot i = start + i × 8
Whether i is 0 or 999999, it is one multiplication and one addition, then follow the reference to the object. That is what "random access is O(1)" means. It is also why indexes start at 0: an index is "how many slots from the start".
iUse a dict as "memory" (the keys are addresses) and work it out yourself:
1start = 0x10002size = 8 # one reference per slot: 8 bytes3memory = {}4values = [10, 20, 30, 40, 50, 60, 70, 80]5for i in range(len(values)):6 memory[start + i * size] = values[i]7 8def get(i):9 addr = start + i * size10 return hex(addr), memory[addr]11 12print(get(0))13print(get(5))14print(get(7))
('0x1000', 10)
('0x1028', 60)
('0x1038', 80)
A negative index a[-1] is just as fast: first work out i + len(a), then use the same formula. len(a) itself is a number the list object keeps, so it is O(1) too.
A list of length 6 has its slots starting at 0x2000. Working out a[-1] by the list's rules, what does it print?
1start = 0x20002size = 83n = 64i = -15if i < 0:6 i += n7print(i, hex(start + i * size))
The slots start at 1000 (decimal), 8 bytes each. What is the address of the slot for a[6]?
Work out a slot's address
✓Finish addr(start, size, n, i): for a list of length n whose slots start at start, size bytes each, return the address of the slot a[i]. i can be negative, with the same rule as a list.
0x1000 0x1018 0x1020 0x100c
1def addr(start, size, n, i):2 # add n to a negative index first, then start + i × slot size3 return start4 5print(hex(addr(0x1000, 8, 5, 0)))6print(hex(addr(0x1000, 8, 5, 3)))7print(hex(addr(0x1000, 8, 5, -1)))8print(hex(addr(0x1000, 4, 5, -2)))
Two-dimensional tables: one list per row
In Python a two-dimensional table is usually a list of lists: m = [[1, 2, 3], [4, 5, 6]]. Each slot of the outer list is a reference to a whole row, and each row is a list of its own. Getting m[1][2] takes two steps: work out slot 1 of the outer list, follow the reference to row 1, then work out slot 2 of that row. Both steps are O(1), so together they are still O(1).
Names
mOuter list: one reference per slot
[0]ref[1]refEach row is its own list
Two-dimensional arrays in C and in numpy are laid out differently: there are no outer references, and all the numbers are spread out row after row in one long strip. This is called row-major order. To find m[i][j], skip the i whole rows in front, then go j further:
address of m[i][j] = start + (i × number of columns + j) × slot size
Exams love this address calculation; note that you multiply by the number of columns. Flatten the list of lists into one strip in Python and take an item by the formula: it is the same number as m[i][j]:
1m = [[1, 2, 3], [4, 5, 6]]2cols = 33flat = [x for row in m for x in row]4print(flat)5i, j = 1, 26print(m[i][j], flat[i * cols + j])
[1, 2, 3, 4, 5, 6] 6 6
Row-major, 3 rows × 4 columns, starting at 1000, 4 bytes per slot. What is the address of m[2][1]?
1start, size = 1000, 42cols = 43i, j = 2, 14print(start + (i * cols + j) * size)
int m[4][5] is stored row by row, starting at 1000, 4 bytes per slot. What is the address of m[3][2]?
Out of range: Python stops you
For a list of length n the valid indexes are 0 to n − 1 (or −n to −1 counting from the end). The address formula does not care: a[5] still gives an address, it just is not one of this list's slots any more. C does not check, and reads or overwrites someone else's data; Python compares the index with the length before working out the address, and if it is out of range it raises IndexError and never touches that memory.
a[5] = 99no errorquietly overwrites the variable next doora[5] = 99IndexErrorchecks the index against the length and stops1a = [10, 20, 30, 40, 50]2print(a[4], a[-5])3try:4 print(a[5])5except IndexError as e:6 print("IndexError:", e)
50 10 IndexError: list index out of range
The most common way to go out of range is a loop that runs one step too far: while i <= len(a), range(len(a) + 1). Writing for x in a, or range(len(a)), avoids it.
a has 5 elements. Which raises IndexError?
a[-5] has the length added first and becomes 0, the first item; a[5] is 5 slots from the start, already past the end of the list, so Python raises IndexError.This loop runs one step too far and raises IndexError. Change only the number in the green box so that it adds up exactly the 5 elements and prints 150.
1a = [10, 20, 30, 40, 50]2total = 03i = 04while i <= :5 total += a[i]6 i += 17print(total)
150
i <= 4, which is the usual i < 5 or i < len(a).Compare: a linked list has to walk
In a linked list (lesson 4 covers it), each value lives in a node object, the nodes are scattered around memory, and each one only points at the next through next. There is no "start + i × 8" to work out: to get item i, follow next from the front i times.
cur↓1cur = head2for _ in range(3):3 cur = cur.next4print(cur.val)
Count the steps each one takes:
1class Node:2 def __init__(self, val, next=None):3 self.val = val4 self.next = next5 6n = 10007head = None8for v in range(n - 1, -1, -1):9 head = Node(v, head)10nums = list(range(n))11 12def get_linked(head, i):13 steps = 014 cur = head15 for _ in range(i):16 cur = cur.next17 steps += 118 return cur.val, steps19 20print("list:", nums[999], "one address worked out")21print("linked list:", get_linked(head, 999))22print("linked list:", get_linked(head, 10))
list: 999 one address worked out linked list: (999, 999) linked list: (10, 10)
| list (a row of references) | linked list (nodes + next) | |
|---|---|---|
| In memory | references side by side, one block | nodes scattered, joined by next |
| Get item i | O(1): start + i × 8 | O(i): walk i steps from the front |
| Extra per item | one reference, 8 bytes | a whole node object |
| Insert at the front | O(n): everything moves (next lesson) | O(1): change one next (lesson 5) |
In interviews: "Why is array random access O(1)?" Give the address formula: start + i × slot size. "Is a Python list a linked list?" No: in CPython it is a contiguous block of references (a PyObject * array), which is why a[i] is fast and insert(0, x) is slow.
A million elements, and you want number 999999. How many steps for a list, and for a linked list?
Item i of a linked list
✓Finish get(head, i): follow next from head i times and return that node's val; if the list is not that long, return None.
10 40 None
1class Node:2 def __init__(self, val, next=None):3 self.val = val4 self.next = next5 6def get(head, i):7 # cur starts at head and takes i steps; reaching None on the way means it is too short8 return None9 10head = Node(10, Node(20, Node(30, Node(40, Node(50)))))11print(get(head, 0), get(head, 3), get(head, 5))
How you write it at work
Getting by index is what a list does best; finding by value is not. x in a, a.index(x) and a.count(x) all compare one by one from slot 0, O(n):
1nums = list(range(0, 20000, 2))2looks = 03 4def contains(a, x):5 global looks6 for v in a:7 looks += 18 if v == x:9 return True10 return False11 12print(contains(nums, 19998), looks)13 14seen = set(nums)15print(19998 in seen)
True 10000 True
The last number took 10000 comparisons to find. A few everyday habits:
a[i],a[-1],len(a)anda[i] = xare all O(1): use them freely.- If you look things up by value again and again ("have I seen this id?"), build a
setordictfirst, O(1) on average; a list'sinis O(n) every time. - A list holds references, and every number in it is a separate int object. For number crunching on millions of values, use an array that stores the numbers themselves side by side, such as numpy: far less memory and much faster.
Searching by value for 8, comparing slot by slot from slot 0. How many comparisons?
1nums = list(range(0, 20, 2))2looks = 03for v in nums:4 looks += 15 if v == 8:6 break7print(looks)
Summary
A list is a row of references, so a[i] is O(1)
- A list object is references side by side, every slot the same size (8 bytes)
- Address of slot i = start + i × 8: one multiplication, one addition
- Slots hold only references, which is how they are all one size; the objects live elsewhere
- A linked list reaches item i only by following next i times: O(n)
- x in a and a.index(x) compare from the front: O(n); look up by value with a set or dict
- A 2D list is one list per row; the row-major address is start + (i × columns + j) × slot size
1a[i] # O(1): start + i * 82a[-1] # O(1): i + len(a) first3x in a # O(n): one by one4x in seen # seen is a set: O(1) on average