Python · Dynamic array · container
list
Python's built-in growable array of object references: O(1) indexing and amortized O(1) append at the end.
# built in: no import class list(iterable=(), /)
CPython 3.14 (sort stability guaranteed since 2.2; behaviour shown is the language guarantee except where marked CPython)
Operations
| Operation | Time | Worst case | Changes the collection |
|---|---|---|---|
| append / extend | O(1) per element | O(n) when the array must be reallocated | Yes |
| insert | O(n) at the front | O(n) at the front | Yes |
| pop | O(n) for pop(0) | O(n) for pop(0) | Yes |
| items[i] and slicing | O(k) for a slice of k elements | O(k) for a slice of k elements | Yes |
| x in items / index | O(n) | O(n) | No |
| sort / sorted | O(n log n) | O(n log n) | Yes |
"Time" shows the amortized, expected or average bound when one applies; open an operation for the full profile and its assumptions.
How it works
- Representation
- In CPython, a C array of pointers to objects plus a size and an allocated count. Growth over-allocates by roughly 1/8 plus a small constant (capacities observed while appending from empty on CPython 3.14.0: 4, 8, 16, 24, 32, 40, 52, 64).
- Ordering
- Insertion order.
- Duplicates
- Allowed.
- Mutability
- Mutable. Modifying a list while iterating over it does not raise but skips or repeats elements: iterate over a copy or build a new list.
- Memory and ownership
- Stores references, so every element is a separate object (a list of ints is not a packed array; array.array or NumPy are). Spare capacity is reclaimed when the list shrinks enough.
- Equality and comparison
- `in`, index, remove and count compare with == (after an identity check). sort compares with < or the key function.
Pitfalls
- insert(0, x) and pop(0) shift every element: O(n). Use collections.deque for queues.
- [[0] * 3] * 3 repeats the same inner list three times; use a comprehension.
- Slicing copies: items[1:] costs O(k) time and memory.
- Negative indices count from the end, so an off-by-one can silently read the wrong element instead of raising.
Alternatives
- collections.deque for both ends
- array.array for packed numbers
- tuple for immutable sequences
- bisect module on a sorted list for ordered lookups
In other languages
- C#: List<T>
- Java: ArrayList<E>
- C++: std::vector<T>