Kodewick
Start learning →
Inside a list: a row of references6 / 52

Inside a list: a row of references

Lesson 6 of 52 · Part 2 · Names, lists and linked lists · about 18 minutes

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

a
b

The list object: a row of references

0x1000[0]ref
0x1008[1]ref
0x1010[2]ref

Objects

10int
'hi'str
[1, 2]list

The list object is 3 slots side by side, 8 bytes each, holding only references; the objects live elsewhere (addresses are examples)
main.py
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])
Output
[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.

Choose one

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".

a (starts at 0x1000)102030405060708001234567↑i

8 slots starting at 0x1000, 8 bytes each (the boxes show values; really they hold references to them): to get item i, work out the address and you are there

Use a dict as "memory" (the keys are addresses) and work it out yourself:

main.py
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))
Output
('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.

Guess the outputA wrong guess is fine

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))
Choose one

The slots start at 1000 (decimal), 8 bytes each. What is the address of the slot for a[6]?

Exercise 1

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.

It should print
0x1000
0x1018
0x1020
0x100c
exercise1.py
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)))
Output
Press Run or Ctrl+Enter

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

m

Outer list: one reference per slot

0x1000[0]ref
0x1008[1]ref

Each row is its own list

[1, 2, 3]list
[4, 5, 6]list

m = 1, 2, 3], [4, 5, 6: the outer list has 2 slots, each pointing at a row (addresses are examples)

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

012row 0123row 1456
in memory: row after row
123456
2 rows × 3 columns in row-major order: row 0 first, then row 1 right after; 1 × 3 + 2 = 5 come before m[1][2]

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]:

main.py
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])
Output
[1, 2, 3, 4, 5, 6]
6 6
Guess the outputA wrong guess is fine

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)
Choose one

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.

Ca[5] = 99no errorquietly overwrites the variable next door
Pythona[5] = 99IndexErrorchecks the index against the length and stops
a has only 5 elements, and both write a[5] = 99
main.py
1a = [10, 20, 30, 40, 50]2print(a[4], a[-5])3try:4    print(a[5])5except IndexError as e:6    print("IndexError:", e)
Output
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.

Choose one

a has 5 elements. Which raises IndexError?

Change it

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)
Should print
150

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↓
10a
20b
30c
40d
50e
None
1cur = head2for _ in range(3):3    cur = cur.next4print(cur.val)

A linked list's nodes are scattered, so you can only follow next one at a time: item 3 takes 3 steps

Count the steps each one takes:

main.py
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))
Output
list: 999 one address worked out
linked list: (999, 999)
linked list: (10, 10)
list (a row of references)linked list (nodes + next)
In memoryreferences side by side, one blocknodes scattered, joined by next
Get item iO(1): start + i × 8O(i): walk i steps from the front
Extra per itemone reference, 8 bytesa whole node object
Insert at the frontO(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.

Choose one

A million elements, and you want number 999999. How many steps for a list, and for a linked list?

Exercise 2

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.

It should print
10 40 None
exercise2.py
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))
Output
Press Run or Ctrl+Enter

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):

main.py
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)
Output
True 10000
True

The last number took 10000 comparisons to find. A few everyday habits:

  • a[i], a[-1], len(a) and a[i] = x are all O(1): use them freely.
  • If you look things up by value again and again ("have I seen this id?"), build a set or dict first, O(1) on average; a list's in is 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.
Guess the outputA wrong guess is fine

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

Take-away

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