Skip to content

Which data structure

This guide picks the container for a job: built-in collections, the collections and heapq tools, record types, NumPy arrays and DataFrames. It gives the big-O cost of common operations and the memory per element. The rules apply to any Python program, not only to data work.

flowchart TD
    A{"Many numbers,<br/>math on whole columns?"} -->|yes| B{"Named columns,<br/>mixed types?"}
    B -->|yes| DF["DataFrame<br/>pandas / Polars"]
    B -->|no| NP["NumPy array"]
    A -->|no| C{"Find values by a key?"}
    C -->|yes| D{"Count or group?"}
    D -->|count| CT["Counter"]
    D -->|group| DD["defaultdict(list)"]
    D -->|neither| DI["dict"]
    C -->|no| E{"Only membership<br/>or uniqueness?"}
    E -->|yes| S["set / frozenset"]
    E -->|no| F{"One record with<br/>named fields?"}
    F -->|yes| R["dataclass / NamedTuple"]
    F -->|no| G{"Add or take at both ends,<br/>or keep the last n?"}
    G -->|yes| DQ["deque"]
    G -->|no| H{"Always need the<br/>smallest or the top k?"}
    H -->|yes| HQ["heapq on a list"]
    H -->|no| L["list<br/>tuple if it never changes"]
I want to… Use… Example
keep items in order, change them later list orders.append(order)
a fixed sequence, a function’s several results tuple return low, high
a key made of several values tuple as a dict key totals[("S01", "2024-03")]
find a value by its id dict prices["P001"]
a default for a missing key d.get(k, default) stock.get("P099", 0)
test “have I seen this?” fast set if order_id in seen:
unique values in first-seen order dict.fromkeys(items) list(dict.fromkeys(ids))
shared and different members set operators &, -, ^ bought_a & bought_b
a set as a dict key or set member frozenset {frozenset({"tea", "milk"}): 3}
count items Counter Counter(words).most_common(3)
group items into lists by key defaultdict(list) by_store[s].append(row)
sum values per key defaultdict(float) or Counter revenue[region] += amount
a FIFO queue deque + popleft() queue.popleft()
a stack (LIFO) list + append() / pop() stack.pop()
keep only the last n items deque(maxlen=n) deque(maxlen=7)
always take the smallest next heapq.heappush / heappop a task scheduler
top k of many items heapq.nlargest(k, it, key=...) top 3 orders
insert into a list that stays sorted bisect.insort insort(times, t)
find a position in sorted data bisect.bisect_left the first reading after t
a record with named fields and defaults @dataclass Order(id="O1", qty=2)
a small, immutable record you can unpack NamedTuple lat, lon = point
millions of small records @dataclass(slots=True) or a DataFrame
type hints for JSON dicts TypedDict class Payload(TypedDict): id: int
a read-only view of a dict types.MappingProxyType(d) expose config safely
layered settings (CLI over env over defaults) ChainMap(cli, env, defaults) first match wins
fast math on many numbers NumPy array prices * 1.2
a table with named, typed columns pandas or Polars DataFrame df.groupby("region")["revenue"].sum()
compact numbers without NumPy array.array("d", values) 8 bytes per float
bytes you change in place bytearray network buffers
Structure Ordered Mutable Hashable Duplicates Find by Best for
list yes yes no yes position sequences, stacks, sort and slice
tuple yes no if its items are yes position fixed records, dict keys, return values
dict insertion order yes no unique keys key lookups, mappings, JSON
set no yes no no value membership, uniqueness, set algebra
frozenset no no yes no value sets as keys
deque yes yes no yes ends queues, sliding windows
heapq list heap order only yes no yes smallest priority queues, top k
Counter insertion order yes no unique keys key counts, histograms of values
defaultdict insertion order yes no unique keys key grouping, accumulating
@dataclass fields in order yes (or frozen) if frozen=True — attribute records with defaults and methods
NamedTuple yes no if its items are — attribute or position small immutable records
NumPy ndarray yes values yes, size no no yes position, mask numeric vectors and matrices
pandas DataFrame yes yes no yes label, mask mixed-type tables, groupby, joins
Polars DataFrame yes methods return new frames no yes expression fast tables, lazy pipelines

Average case. nn is the size of the container, kk the number of items asked for.

Operation list dict / set deque heapq sorted list + bisect NumPy array
get item i O(1)O(1) — O(n)O(n) in the middle, O(1)O(1) at the ends O(1)O(1) (only h[0] is meaningful) O(1)O(1) O(1)O(1)
x in c O(n)O(n) O(1)O(1) O(n)O(n) O(n)O(n) O(log⁡n)O(\log n) with bisect O(n)O(n), vectorized
add at the end O(1)O(1) amortized O(1)O(1) O(1)O(1) O(log⁡n)O(\log n) push O(n)O(n) insort O(n)O(n): copies the array
add or remove at the front O(n)O(n) — O(1)O(1) — O(n)O(n) O(n)O(n)
remove a given value O(n)O(n) O(1)O(1) O(n)O(n) O(n)O(n) O(n)O(n) O(n)O(n) (new array)
smallest item O(n)O(n) O(n)O(n) O(n)O(n) O(1)O(1) peek, O(log⁡n)O(\log n) pop O(1)O(1) O(n)O(n), vectorized
top k O(nlog⁡k)O(n \log k) with nlargest O(nlog⁡k)O(n \log k) O(nlog⁡k)O(n \log k) O(klog⁡n)O(k \log n) O(k)O(k) O(n)O(n) with np.partition
sort O(nlog⁡n)O(n \log n) via sorted() via sorted() O(nlog⁡n)O(n \log n) already sorted O(nlog⁡n)O(n \log n)
sum of all values O(n)O(n), Python loop O(n)O(n) O(n)O(n) O(n)O(n) O(n)O(n) O(n)O(n) in C: 10–100× faster

“Amortized” means the average over many calls: a list sometimes grows its storage, and that one call is slower. Dict and set operations are O(1)O(1) on average and degrade only when many keys hash to the same slot.

A DataFrame follows its columns: a column is an array, so whole-column math is vectorized and fast. Row-by-row loops (iterrows, apply(axis=1)) are Python loops, often 100× slower than a column expression. Appending one row copies the frame: collect rows in a list, then build the frame once.

import timeit
ids = [f"C{n:05d}" for n in range(1, 5001)]
id_set = set(ids)
t_list = timeit.timeit('"C05000" in ids', globals=globals(), number=200)
t_set = timeit.timeit('"C05000" in id_set', globals=globals(), number=200)
print("set lookup at least 50x faster:", t_set * 50 < t_list)
Output
set lookup at least 50x faster: True
import sys
from collections import deque
import numpy as np
items = list(range(1_000))
containers = {
"list": items,
"tuple": tuple(items),
"set": set(items),
"dict": dict.fromkeys(items),
"deque": deque(items),
}
for name, c in containers.items():
print(f"{name:<6} {sys.getsizeof(c):>7,} bytes") # the container only
print(f"ints {sum(sys.getsizeof(i) for i in items):>7,} bytes") # the int objects
print(f"array {np.arange(1_000).nbytes:>7,} bytes") # raw int64 values, no objects
Output
list 8,056 bytes
tuple 8,040 bytes
set 32,984 bytes
dict 36,952 bytes
deque 8,680 bytes
ints 28,000 bytes
array 8,000 bytes
Structure Bytes per element (64-bit CPython) Notes
list, tuple 8 (a pointer) + the object a tuple is a little smaller and never over-allocates
int, float object 28 and 24 each boxed number is a full object
set, dict about 30–60 + the objects a hash table keeps empty slots for speed
deque about 8 + the objects blocks of 64 pointers
instance of a plain class about 100 with its attribute storage measure: CPython 3.11+ stores attributes compactly
@dataclass(slots=True) instance 48 for two fields (sys.getsizeof, CPython 3.13) no per-object __dict__; 8 more per field
NumPy int64 / float64 8, no object per value int32, float32 halve it
pandas numeric column 8 + the index df.memory_usage(deep=True)
pandas str column the text itself (Arrow storage) category dtype for few distinct values
Polars column Arrow buffers: 8 per number, text in one buffer df.estimated_size("mb")

sys.getsizeof is shallow: it counts the container, not the objects it points to. For a whole structure, use tracemalloc or df.memory_usage(deep=True).

Tool Import Key methods Use it for
deque from collections import deque append, appendleft, pop, popleft, rotate, maxlen= queues, BFS, last-n windows
Counter from collections import Counter most_common(k), update, total(), +, -, & counts, top values, multisets
defaultdict from collections import defaultdict defaultdict(list), (int), (set) grouping, accumulating
OrderedDict from collections import OrderedDict move_to_end, popitem(last=False) LRU caches; order-sensitive ==
ChainMap from collections import ChainMap new_child, .maps layered lookups, scopes
heapq import heapq heappush, heappop, heapify, nlargest, nsmallest, merge priority queues, top k, merging sorted streams
bisect import bisect bisect_left, bisect_right, insort sorted lists, bands and thresholds
array import array array("d", values) compact numbers without NumPy
Need Use Why
quick script, keys not known in advance dict no class needed
JSON in, JSON out dict + TypedDict hints stays a dict; the type checker checks keys
a small result that callers unpack NamedTuple name, score = best
defaults, methods, light validation @dataclass readable, typed, standard library
must not change, used as a key @dataclass(frozen=True) or NamedTuple hashable
millions of records a DataFrame, or @dataclass(slots=True) columns beat objects
untrusted input to validate and convert pydantic BaseModel coercion and clear errors

Details for each record type are on the data containers page.

Data Choose Why not the others
a few hundred mixed values list / dict NumPy and pandas have a start-up and per-call cost
one numeric vector or a matrix NumPy array a list of floats is about 4× larger and 10–100× slower to sum
an image, a tensor NumPy array (PyTorch tensor for training) n-dimensional, one dtype
a table of mixed column types pandas or Polars DataFrame a NumPy array has one dtype for all cells
rows of records from an API list[dict], then pd.DataFrame(rows) build the frame once, not row by row
a table larger than memory Polars lazy with the streaming engine, or DuckDB pandas loads everything; a plain collect() loads the result too

See pandas vs Polars vs SQL for the table libraries.

The scenarios use the orders in data/sales.csv, read with the standard library:

import csv
import heapq
from collections import Counter, defaultdict
with open("data/sales.csv", newline="", encoding="utf-8") as f:
rows = list(csv.DictReader(f)) # list[dict[str, str]]
print(len(rows), rows[0]["order_id"], rows[0]["customer_id"])
Output
20228 O000001 C00618

Unique customers in first-seen order. A set loses the order. dict.fromkeys keeps it.

customers = list(dict.fromkeys(r["customer_id"] for r in rows))
print(len(customers), customers[:3])
Output
3254 ['C00618', 'C00971', 'C01140']

The best-selling categories. Counter counts in one pass and sorts the result.

units = Counter()
for r in rows:
units[r["category"]] += int(r["quantity"])
print(units.most_common(3))
Output
[('Clothing', 6522), ('Beauty', 5491), ('Sports', 4547)]

All orders of each store. defaultdict(list) creates the empty list on first use.

by_store: defaultdict[str, list[float]] = defaultdict(list)
for r in rows:
by_store[r["store_id"]].append(float(r["revenue"]))
print(len(by_store), round(sum(by_store["S01"]), 2))
Output
12 406532.46

A total per compound key. A tuple of values is a valid dict key; a list is not.

monthly: defaultdict[tuple[str, str], float] = defaultdict(float)
for r in rows:
monthly[(r["region"], r["order_date"][:7])] += float(r["revenue"])
print(round(monthly[("North", "2024-12")], 2))
Output
78630.15

The three largest order lines. heapq.nlargest keeps only k items in memory: O(nlog⁡k)O(n \log k), not a full sort.

top = heapq.nlargest(3, rows, key=lambda r: float(r["revenue"]))
print([(r["order_id"], r["revenue"]) for r in top])
Output
[('O001531', '5196.0'), ('O006934', '4596.0'), ('O011849', '4596.0')]

A rolling window of the last 3 values. deque(maxlen=3) drops the oldest item on each append.

from collections import deque
window = deque(maxlen=3)
for value in [12.0, 15.0, 11.0, 18.0, 20.0]:
window.append(value)
print(list(window), round(sum(window) / len(window), 2))
Output
[12.0] 12.0
[12.0, 15.0] 13.5
[12.0, 15.0, 11.0] 12.67
[15.0, 11.0, 18.0] 14.67
[11.0, 18.0, 20.0] 16.33

A priority queue. A counter in the tuple breaks ties, so Python never compares the payloads.

from itertools import count
tasks: list[tuple[int, int, str]] = []
order = count()
for priority, name in [(2, "email report"), (1, "restart api"), (2, "rotate logs")]:
heapq.heappush(tasks, (priority, next(order), name)) # the lowest number pops first
print([heapq.heappop(tasks)[2] for _ in range(len(tasks))])
Output
['restart api', 'email report', 'rotate logs']
Trap Symptom Fix
x in big_list inside a loop the loop is quadratic and slow build a set once, before the loop
list.pop(0) or insert(0, x) as a queue slow on long lists deque.popleft(), appendleft()
a list, dict or set as a dict key TypeError: unhashable type: 'list' a tuple or a frozenset
[[0] * 3] * 3 changing one row changes all rows [[0] * 3 for _ in range(3)]
b = a changes to b show in a a.copy(); copy.deepcopy(a) for nested data
{} for an empty set you get a dict set()
printing a set of strings the order changes between runs sorted(s)
d[k] on a missing key KeyError d.get(k), defaultdict, or k in d first
defaultdict read with d[k] the read inserts an empty value d.get(k) or k in d for reads
a printed heap list it looks unsorted only h[0] is the smallest; pop, or sorted(h)
(priority, dict) on a heap TypeError when two priorities are equal (priority, counter, item)
bisect on unsorted data a wrong position, no error sort first
a Counter with negative counts most_common shows odd items +c drops counts ≤ 0
deque[i] in the middle slow random access a list
growing a NumPy array with np.append in a loop each call copies: quadratic collect in a list, call np.array once
pd.concat one row at a time slow, quadratic build a list[dict], then one DataFrame
sys.getsizeof(container) as the total size far too small tracemalloc, df.memory_usage(deep=True)
a frozen dataclass with a list field the list still changes; hash() fails store a tuple
a NamedTuple compared with a tuple Point(1, 2) == (1, 2) is True a frozen dataclass when the type matters