Skip to content

Data structures

First PublishedByAtif Alam
xs = [1, 2, 3] # list — ordered, mutable (dynamic array)
t = (1, 2) # tuple — ordered, immutable
d = {"a": 1, "b": 2} # dict — key–value; insertion order preserved (3.7+)
s = {1, 2, 3} # set — unordered, unique, hashable elements only
f = frozenset({1, 2}) # frozenset — immutable set
name = "hello" # str — immutable character sequence
b = b"bytes" # bytes — immutable; bytearray — mutable

Empty: [] list, {} dict, set() set (not {} — that’s a dict).

  • Mutable = can change in place (list, dict, set). Immutable = can’t (tuple, str, frozenset, int).
  • Only hashable types can be dict keys or set elements. Immutable built-ins (tuple, str, frozenset, int, float) are hashable; list, dict, and set are not. That’s why you can’t put a list in a set or use it as a dict key — use a tuple instead.
  • collections: deque (double-ended queue), defaultdict, Counter, OrderedDict, namedtuple
  • heapq: min-heap on a list
  • queue: Queue, LifoQueue, PriorityQueue (thread-safe)
  • array: typed arrays

Third-party: NumPy, Pandas, and graph/tree libs for specialized needs.

Use caseStructure
Ordered sequence you need to changelist (append, insert, remove) — default for “a sequence of things”
Ordered sequence that shouldn’t changetuple (return values, dict keys, coordinates)
Look up by keydict (names → values, id → record)
Unique items or fast “is x in here?”set (order doesn’t matter, no duplicates)
Queue or stack from both endsdeque (use instead of list when you pop from the front often, e.g. BFS)
Smallest item, priority queue, “top K”heapq (min-heap)

These structures are the base you’ll use when learning algorithms:

  • list — dynamic array (indexing, sorting, DP)
  • dict — O(1) lookup and graph adjacency
  • set — visited sets and uniqueness
  • tuple — immutable pairs (edges, coords)
  • deque — BFS and queues
  • heapq — Dijkstra and heaps

See the Algorithms section for more.