Lists
A list is Python's built-in mutable sequence: an ordered, resizable collection of references to objects, indexed from zero. It is the default container you reach for when order matters and the size is not known in advance.
Detailed Explanation
A list is a dynamic array. CPython stores a contiguous block of pointers, one per element, plus a length and a capacity. The elements themselves live elsewhere on the heap; the list only holds references to them. That is why a list can mix types freely: every slot is the same size, a pointer, regardless of what it points at.
Contiguous pointers are what make indexing fast. prices[4000] is one multiplication and one memory read, no matter how long the list is. It is also what makes the front of a list expensive. queue.pop(0) must shift every remaining pointer one slot left, so it costs O(n). Beginners write breadth-first search with pop(0) and wonder why it crawls on large inputs; the fix is collections.deque.
Appending is fast because CPython over-allocates. When a list runs out of capacity it asks for more room than it needs, following a growth pattern of roughly 0, 4, 8, 16, 25, 35, 46, 58, 72, 88 slots. Most appends therefore write into spare capacity and cost O(1). Occasionally an append triggers a reallocation and copy, which is O(n). Spread across many appends the cost averages out, which is what "amortised O(1)" means. The trade-off is memory: a list is usually a little larger than its contents require.
| Operation | Average | Worst case | Why |
|---|---|---|---|
items[i], items[i] = v | O(1) | O(1) | Pointer arithmetic into a contiguous block |
len(items) | O(1) | O(1) | Length is stored, not counted |
items.append(x) | O(1) amortised | O(n) | Occasional reallocation and copy |
items.pop() | O(1) | O(1) | Removes from the end, nothing shifts |
items.insert(0, x) | O(n) | O(n) | Every later pointer shifts right |
items.pop(0), del items[0] | O(n) | O(n) | Every later pointer shifts left |
x in items | O(n) | O(n) | Linear scan comparing element by element |
items.remove(x) | O(n) | O(n) | Scan to find, then shift |
items.sort() | O(n log n) | O(n log n) | Timsort, in place |
items[a:b] | O(k) | O(k) | Copies k pointers into a new list |
Lists are mutable, so every name bound to a list sees every change. They are also unhashable for exactly that reason: a hash that could change under you would break every dict and set holding it. When you need a sequence that can be a dict key, use a tuple.
Reach for a list when you need ordering, duplicates, indexing, or in-place growth at the end. Reach for a set or a dict when your real question is "have I seen this?", because that turns an O(n) scan into an O(1) average lookup.
Code Examples
# A list is ordered, indexable, and holds references to any objects.
temperatures = [18.2, 21.7, 19.4, 25.1]
print(temperatures[0]) # 18.2
print(temperatures[-1]) # 25.1 <- negative indices count from the end
print(temperatures[1:3]) # [21.7, 19.4] <- a slice is a NEW list
temperatures.append(23.8) # amortised O(1): writes into spare capacity
temperatures.insert(0, 15.0) # O(n): every other element shifts right
print(temperatures) # [15.0, 18.2, 21.7, 19.4, 25.1, 23.8]
# sort() reorders in place and returns None; sorted() returns a new list.
temperatures.sort()
print(temperatures) # [15.0, 18.2, 19.4, 21.7, 23.8, 25.1]# Membership on a list is a linear scan. On a set it is a hash lookup.
blocked_domains = ["spam.example", "bad.example", "phish.example"]
print("bad.example" in blocked_domains) # True, but O(n) each time
blocked_lookup = set(blocked_domains) # build once, O(n)
print("bad.example" in blocked_lookup) # True, O(1) average
# Repetition copies REFERENCES, not objects.
grid = [[0] * 3] * 3 # three names for the SAME inner list
grid[0][0] = 9
print(grid) # [[9, 0, 0], [9, 0, 0], [9, 0, 0]] <- all rows changed
grid = [[0] * 3 for _ in range(3)] # one fresh inner list per row
grid[0][0] = 9
print(grid) # [[9, 0, 0], [0, 0, 0], [0, 0, 0]]Common Gotchas
A default argument is created once
`def log(msg, seen=[])` reuses the same list on every call, so entries accumulate across calls. Use `seen=None` and create the list inside the function body.
Do not mutate a list while iterating it
`for item in batch: batch.remove(item)` skips elements, because the index advances while the list shrinks. Iterate over a copy, `for item in list(batch)`, or build a new list with a comprehension.
`sort()` returns `None`
`items = items.sort()` silently sets `items` to `None`. Use `items.sort()` for in-place ordering, or `sorted(items)` when you want a new list back.