Language collection paths · 6 steps

Python collections

The five core Python collections in the order you need them, each paired with the structure underneath, a visualizer and a problem that uses it.

Who it is for
Python developers who want to know what the standard collections cost and which one to reach for.
By the end
You can choose between the core Python collections by operation cost and avoid the usual misuse of each.
  1. Step 2: Dynamic array

    The default sequence. list.append is amortized O(1); insert(0, x) and pop(0) are O(n), which is why queues use deque.

  2. Step 3: Hash map

    Lookup by key in expected O(1). d[key] raises KeyError for a missing key; get, setdefault and collections.Counter cover the common cases.

  3. Step 4: Hash set

    Membership without values. set.add does not report whether the value was new; test membership with `in` first when that matters.

  4. Step 5: Queue and deque

    First in, first out, the order BFS needs. collections.deque is O(1) at both ends; indexing into the middle is O(n).

  5. Step 6: Priority queue

    Repeatedly take the smallest (or largest) item. heapq is a set of functions on a plain list and implements a min-heap; negate keys for a max-heap.