Skip to content

Collections and comprehensions

The built-in containers and the collections module: what each operation costs, how to unpack and copy safely, and every comprehension form. Every runnable block is checked against its output.

I want to… Use… Example
add one item to the end xs.append(x) O(1)
add many items xs.extend(items) or xs += items
insert or remove at the front often collections.deque dq.appendleft(x), dq.popleft()
remove by position xs.pop(i) / del xs[i] xs.pop() removes the last
remove by value xs.remove(x) (first match; ValueError if absent)
sort in place / get a sorted copy xs.sort() / sorted(xs) sorted(xs, key=len, reverse=True)
sort by several keys key returns a tuple sorted(rows, key=lambda r: (r["region"], -r["revenue"]))
find the position of a value xs.index(x) ValueError if absent
test membership fast a set or dict x in seen is O(1)
remove duplicates, keep order list(dict.fromkeys(xs))
remove duplicates, order does not matter set(xs)
get a value with a default d.get(k, default) no KeyError
add a key only if missing d.setdefault(k, default) returns the value
group items into lists defaultdict(list) groups[key].append(item)
count things Counter(items) .most_common(3)
merge two dicts a | b (right wins), a |= b {**a, **b} also works
sort a dict by value sorted(d.items(), key=lambda kv: kv[1]) dict(...) to rebuild
invert a dict {v: k for k, v in d.items()} values must be unique and hashable
loop over keys and values for k, v in d.items():
delete keys while looping loop over list(d) changing size during iteration raises
combine, intersect, subtract sets a | b, a & b, a - b, a ^ b
check a subset a <= b, a.issubset(b)
use a set or list as a dict key frozenset(s), tuple(xs) keys must be hashable
unpack first and rest first, *rest = xs rest is a list
unpack nested data for name, (lat, lon) in places:
copy a flat list xs.copy(), xs[:], list(xs) shallow
copy nested data copy.deepcopy(obj)
make a 2D grid [[0] * cols for _ in range(rows)] never [[0] * cols] * rows
keep the last N items deque(maxlen=N) old items fall off
make a light record type namedtuple or typing.NamedTuple p.x, p._replace(x=1)
layer config defaults and overrides ChainMap(cli, env, defaults) first mapping wins
get the N largest items heapq.nlargest(k, xs, key=...) O(n log k), k = number requested
keep a sorted list as you insert bisect.insort(xs, x)
flatten one level [x for sub in nested for x in sub] or itertools.chain.from_iterable
build a dict from two lists dict(zip(keys, values, strict=True))
transpose a matrix list(zip(*matrix)) rows of tuples
Need Use Why
ordered items, change them, index them list O(1) index and append
a fixed record or a dict key tuple immutable, hashable
lookup by key dict O(1) average get and set
unique items, fast in, set algebra set O(1) average in
a hashable set frozenset dict key, set member
a queue or stack with both ends collections.deque O(1) at both ends
counts per key collections.Counter counting helpers built in
a dict of lists or sets collections.defaultdict no if key not in d
a record with named fields typing.NamedTuple, @dataclass readable attributes
a priority queue heapq on a list O(log n) push and pop
a sorted list bisect on a list O(log n) search
many numbers of one type NumPy array vectorized math, compact memory

n is the container size, k the size of the other argument. “Average” assumes good hashes.

Operation list dict set deque
len(x) O(1) O(1) O(1) O(1)
get by index or key O(1) xs[i] O(1) d[k] — O(n) in the middle, O(1) at ends
set by index or key O(1) O(1) — O(n) in the middle
append at the end O(1) amortized O(1) d[k] = v O(1) add O(1)
add or remove at the front O(n) insert(0, x), pop(0) — — O(1) appendleft, popleft
pop the last O(1) O(1) popitem O(1) pop (arbitrary) O(1)
insert or delete in the middle O(n) O(1) del d[k] O(1) discard O(n)
x in c O(n) O(1) keys O(1) O(n)
iterate O(n) O(n) O(n) O(n)
copy O(n) O(n) O(n) O(n)
sort O(n log n) — — —
slice xs[a:b] O(b − a) — — —
extend / update by k items O(k) O(k) O(k) O(k)
min, max, sum O(n) O(n) O(n) O(n)
union, intersection — | O(n + k) | O(n + k), & O(min(n, k)) —
import time
items = list(range(200_000))
as_set = set(items)
start = time.perf_counter()
for _ in range(200):
found = 199_999 in items # scans the whole list
list_time = time.perf_counter() - start
start = time.perf_counter()
for _ in range(200):
found = 199_999 in as_set # one hash lookup
set_time = time.perf_counter() - start
print("set is faster:", set_time < list_time)
Output
set is faster: True
Method Does Returns
append(x) add one item at the end None
extend(it) add every item of it None
insert(i, x) insert before position i None
pop(), pop(i) remove and return the last or item i the item
remove(x) remove the first x None; ValueError if absent
clear() remove everything None
index(x, start, stop) position of the first x int; ValueError if absent
count(x) number of x int
sort(key=, reverse=) sort in place (stable) None
reverse() reverse in place None
copy() shallow copy new list
xs = [3, 1, 4, 1, 5, 9]
xs.append(2)
xs.extend([6, 5])
xs.insert(0, 0)
print(xs)
print(xs.pop(), xs.pop(0), xs.count(1), xs.index(4), xs) # pop returns the item
xs.remove(1) # first 1 only
print(xs, sorted(xs), sorted(xs, reverse=True), xs[::-1])
xs[1:3] = ["a", "b", "c"] # slice assignment can change the length
del xs[-2:]
print(xs, [0] * 3, [1, 2] + [3])
Output
[0, 3, 1, 4, 1, 5, 9, 2, 6, 5]
5 0 2 2 [3, 1, 4, 1, 5, 9, 2, 6]
[3, 4, 1, 5, 9, 2, 6] [1, 2, 3, 4, 5, 6, 9] [9, 6, 5, 4, 3, 2, 1] [6, 2, 9, 5, 1, 4, 3]
[3, 'a', 'b', 'c', 5, 9] [0, 0, 0] [1, 2, 3]
Fact Example
the comma makes a tuple t = 1, 2 and t = (1,); (1) is an int
immutable, hashable if items are {(0, 0): "origin"}
only two methods t.count(x), t.index(x)
return several values return low, high then lo, hi = f()
a tuple can hold a list t = ([1],); t[0].append(2) works, hash(t) fails
compare item by item (1, 2) < (1, 3); used for multi-key sorts
Operation Example Note
create {"a": 1}, dict(a=1), dict(pairs), dict.fromkeys(keys, 0)
read d["a"] KeyError if missing
read with default d.get("a", 0) None without a default
write d["a"] = 2
write if missing d.setdefault("a", []) returns the stored value
delete del d["a"], d.pop("a", None) pop with a default never raises
last inserted pair d.popitem() LIFO
merge d | other, d |= other, d.update(other) right side wins
views d.keys(), d.values(), d.items() live views; keys and items support set operations
order insertion order (guaranteed since 3.7) re-assigning a key keeps its position
keys any hashable: str, int, tuple, frozenset not list, dict, set
equality {"a": 1, "b": 2} == {"b": 2, "a": 1} True: order does not matter
stock = {"apples": 5, "pears": 0}
stock["kiwis"] = 12
print(stock.get("plums"), stock.get("plums", 0), stock.setdefault("figs", 3))
print(stock.pop("pears"), stock.pop("plums", None), list(stock))
print(stock | {"apples": 7, "limes": 1})
print(sorted(stock.items(), key=lambda kv: kv[1], reverse=True))
print(stock.keys() & {"apples", "limes"}, {v: k for k, v in stock.items()})
for name in list(stock): # copy the keys before deleting
if stock[name] < 5:
del stock[name]
print(stock)
Output
None 0 3
0 None ['apples', 'kiwis', 'figs']
{'apples': 7, 'kiwis': 12, 'figs': 3, 'limes': 1}
[('kiwis', 12), ('apples', 5), ('figs', 3)]
{'apples'} {5: 'apples', 12: 'kiwis', 3: 'figs'}
{'apples': 5, 'kiwis': 12}
Operation Operator Method {1, 2, 3} with {3, 4}
union a | b a.union(b) {1, 2, 3, 4}
intersection a & b a.intersection(b) {3}
difference a - b a.difference(b) {1, 2}
symmetric difference a ^ b a.symmetric_difference(b) {1, 2, 4}
subset, superset a <= b, a >= b issubset, issuperset False, False
proper subset a < b False
no common items a.isdisjoint(b) False
add, remove add(x), remove(x) (KeyError), discard(x) (silent)
in-place update a |= b, a &= b, a -= b update, intersection_update

Methods accept any iterable (a.union([4, 5])); operators need sets on both sides.

seen, dupes = set(), set()
for order_id in ["O1", "O2", "O1", "O3", "O2"]:
(dupes if order_id in seen else seen).add(order_id)
print(sorted(seen), sorted(dupes))
a, b = {1, 2, 3}, {3, 4}
print(a | b, a & b, a - b, a ^ b, {1, 2} <= a, a.isdisjoint({9}))
print(list(dict.fromkeys(["b", "a", "b", "c", "a"]))) # dedupe, keep first-seen order
Output
['O1', 'O2', 'O3'] ['O1', 'O2']
{1, 2, 3, 4} {3} {1, 2} {1, 2, 4} True True
['b', 'a', 'c']
Form Example Result
fixed a, b = (1, 2) counts must match
star first, *rest = [1, 2, 3] rest == [2, 3]
star in the middle head, *mid, tail = "abcd" mid == ['b', 'c']
ignore values _, value = pair, *_, last = xs _ is a convention
nested (x, y), z = (1, 2), 3
in a for for i, (k, v) in enumerate(d.items()):
into a list or tuple [*a, *b], (*a, 0) concatenation of any iterables
into a set {*a, *b}
into a dict {**defaults, **overrides} right side wins
into a call f(*args), f(**kwargs) positional and keyword
transpose list(zip(*rows))
head, *middle, tail = "python"
(lat, lon), name = (41.88, -87.63), "Chicago"
rows = [(1, "a"), (2, "b"), (3, "c")]
ids, letters = zip(*rows) # unzip
defaults, overrides = {"sep": ",", "header": True}, {"sep": ";"}
print(head, middle, tail, lat, name, ids, letters)
print([*ids, *"xy"], {**defaults, **overrides})
Output
p ['y', 't', 'h', 'o'] n 41.88 Chicago (1, 2, 3) ('a', 'b', 'c')
[1, 2, 3, 'x', 'y'] {'sep': ';', 'header': True}
Code Result Inner objects
b = a another name for the same object shared
b = a.copy(), a[:], list(a), dict(a), copy.copy(a) new outer container shared
b = copy.deepcopy(a) new container, new inner objects copied
[[0] * 3] * 2 two references to one inner list shared: a bug
[[0] * 3 for _ in range(2)] two separate inner lists separate
import copy
a = [[1, 2], [3, 4]]
alias, shallow, deep = a, a.copy(), copy.deepcopy(a)
a[0].append(99) # change an inner list
a.append([5]) # change the outer list
print(alias, shallow, deep, sep="\n")
grid_bad = [[0] * 3] * 2
grid_ok = [[0] * 3 for _ in range(2)]
grid_bad[0][0] = grid_ok[0][0] = 1
print(grid_bad, grid_ok)
Output
[[1, 2, 99], [3, 4], [5]]
[[1, 2, 99], [3, 4]]
[[1, 2], [3, 4]]
[[1, 0, 0], [1, 0, 0]] [[1, 0, 0], [0, 0, 0]]
Kind Syntax Example result
list [expr for x in it] [x * x for x in range(4)] → [0, 1, 4, 9]
filtered [expr for x in it if cond]
value choice [a if cond else b for x in it]
filter and choice [a if c1 else b for x in it if c2] if/else before for, filter after
nested loops [expr for x in xs for y in ys] same order as nested for statements
nested filter [x for row in m if row for x in row if x] each for can have an if
nested result [[expr for y in ys] for x in xs] a list of lists
dict {k: v for k, v in it}
dict filter {k: v for k, v in d.items() if v}
set {expr for x in it}
generator (expr for x in it) lazy; consumed once
generator as the only argument sum(x for x in it) no extra parentheses
with walrus [y for x in it if (y := f(x))] call f once per item
with enumerate or zip {name: i for i, name in enumerate(names)}
words = ["apple", "Bob", "", "kiwi", "banana", "Anna"]
print([w.lower() for w in words if w])
print([w if len(w) > 3 else "-" for w in words if w])
print({w: len(w) for w in words if w}, {len(w) for w in words})
matrix = [[1, 2, 3], [4, 5, 6]]
print([x for row in matrix for x in row if x % 2]) # flatten and filter
print([[row[i] for row in matrix] for i in range(3)]) # transpose
print([(r, c) for r in "ab" for c in range(2)])
lengths = (len(w) for w in words)
print(max(lengths), sum(lengths)) # max consumed the generator: the sum is 0
print([n for w in words if (n := len(w)) >= 5])
Output
['apple', 'bob', 'kiwi', 'banana', 'anna']
['apple', '-', 'kiwi', 'banana', 'Anna']
{'apple': 5, 'Bob': 3, 'kiwi': 4, 'banana': 6, 'Anna': 4} {0, 3, 4, 5, 6}
[1, 3, 5]
[[1, 4], [2, 5], [3, 6]]
[('a', 0), ('a', 1), ('b', 0), ('b', 1)]
6 0
[5, 6]
Rule Detail
the loop variable does not leak after [x for x in xs], x is not defined (Python 3)
prefer a loop for side effects [print(x) for x in xs] builds a useless list
keep it to one or two clauses three nested for clauses are hard to read; write a loop
a generator for large data sum(x for x in big) does not build a list
map / filter fine with a named function: list(map(str.strip, lines))
import csv
from collections import Counter
with open("data/sales.csv", newline="", encoding="utf-8") as f:
rows = list(csv.DictReader(f))
by_region = Counter(row["region"] for row in rows)
print(by_region.most_common(2), by_region.total())
channel = Counter(row["channel"] for row in rows[:100])
print(channel, channel["phone"]) # a missing key counts 0, no KeyError
letters = Counter("mississippi")
letters.update("ss") # add counts
letters.subtract({"i": 4}) # counts can go to 0 or below
print(letters.most_common(3), +letters) # unary + drops counts <= 0
print(Counter(a=3, b=1) - Counter(a=1, b=2), Counter(a=3) & Counter(a=1, b=2))
Output
[('East', 5396), ('South', 5144)] 20228
Counter({'store': 72, 'online': 28}) 0
[('s', 6), ('p', 2), ('m', 1)] Counter({'s': 6, 'p': 2, 'm': 1})
Counter({'a': 2}) Counter({'a': 1})
from collections import defaultdict
orders = [("S01", 66.49), ("S02", 14.99), ("S01", 19.99), ("S03", 59.99)]
by_store = defaultdict(list) # missing keys start as []
total = defaultdict(float) # missing keys start as 0.0
for store, revenue in orders:
by_store[store].append(revenue)
total[store] += revenue
print(dict(by_store))
print({store: round(amount, 2) for store, amount in total.items()})
tree = defaultdict(lambda: defaultdict(int)) # nested counts
tree["North"]["S01"] += 1
print({k: dict(v) for k, v in tree.items()})
print("S09" in total, total["S09"], "S09" in total) # reading a missing key adds it
Output
{'S01': [66.49, 19.99], 'S02': [14.99], 'S03': [59.99]}
{'S01': 86.48, 'S02': 14.99, 'S03': 59.99}
{'North': {'S01': 1}}
False 0.0 True
from collections import deque
queue = deque(["a", "b"])
queue.append("c") # right end
queue.appendleft("z") # left end
print(queue)
print(queue.popleft(), queue.pop(), queue)
last3 = deque(maxlen=3) # a sliding window
for reading in [21.0, 21.9, 21.4, 21.7, 22.1]:
last3.append(reading)
print(last3, round(sum(last3) / len(last3), 2))
ring = deque(range(5))
ring.rotate(2)
print(ring)
Output
deque(['z', 'a', 'b', 'c'])
z c deque(['a', 'b'])
deque([21.4, 21.7, 22.1], maxlen=3) 21.73
deque([3, 4, 0, 1, 2])

The choice between namedtuple, NamedTuple, @dataclass and TypedDict is on the data containers page.

from collections import namedtuple
from typing import NamedTuple
Point = namedtuple("Point", ["x", "y"], defaults=[0])
class Store(NamedTuple):
store_id: str
city: str
size_sqm: int = 0
p = Point(3)
s = Store("S01", "Chicago", 2850)
print(p, p.x + p.y, p._replace(y=5), Point._fields)
print(s.city, s._asdict(), s[0], tuple(s) == ("S01", "Chicago", 2850))
Output
Point(x=3, y=0) 3 Point(x=3, y=5) ('x', 'y')
Chicago {'store_id': 'S01', 'city': 'Chicago', 'size_sqm': 2850} S01 True
from collections import ChainMap, OrderedDict
defaults = {"sep": ",", "encoding": "utf-8", "header": True}
user = {"sep": ";"}
settings = ChainMap(user, defaults) # look up in user first, then defaults
print(settings["sep"], settings["encoding"], dict(settings))
settings["header"] = False # writes go to the first mapping only
print(user, defaults["header"])
lru = OrderedDict.fromkeys("abc")
lru.move_to_end("a") # mark "a" as recently used
print(list(lru), lru.popitem(last=False)) # pop the oldest
print(OrderedDict(a=1, b=2) == OrderedDict(b=2, a=1), dict(a=1, b=2) == dict(b=2, a=1))
Output
; utf-8 {'sep': ';', 'encoding': 'utf-8', 'header': True}
{'sep': ';', 'header': False} True
['b', 'c', 'a'] ('b', None)
False True
Class Use Note
Counter counts, histograms, top-N most_common, total() (3.10+), + - & |
defaultdict(factory) group or accumulate reading a missing key creates it
deque(maxlen=n) queues, sliding windows, BFS O(1) at both ends, O(n) indexing in the middle
namedtuple / NamedTuple small immutable records tuple behavior: unpacking, indexing
ChainMap layered settings, scopes writes go to the first mapping
OrderedDict move_to_end, popitem(last=False) dict keeps order too; use OrderedDict for reordering and order-sensitive ==
import bisect
import heapq
revenue = [66.49, 14.99, 19.99, 59.99, 104.5, 8.0]
print(heapq.nlargest(2, revenue), heapq.nsmallest(2, revenue))
tasks = []
for priority, name in [(3, "write"), (1, "fix"), (2, "test")]:
heapq.heappush(tasks, (priority, name)) # smallest first
print([heapq.heappop(tasks)[1] for _ in range(len(tasks))])
cutoffs, grades = [50, 75, 90], "FCBA"
print([grades[bisect.bisect(cutoffs, score)] for score in (42, 75, 99)])
Output
[104.5, 66.49] [8.0, 14.99]
['fix', 'test', 'write']
['F', 'B', 'A']
Trap Symptom Fix
xs = xs.sort() xs is None xs.sort() or xs = sorted(xs)
b = a then change b a changes too a.copy(); copy.deepcopy for nested data
[[0] * 3] * 3 changing one row changes all rows [[0] * 3 for _ in range(3)]
def f(xs=[]) the list keeps items between calls xs=None, then create it inside
removing from a list while looping over it items are skipped loop over a copy, or build a new list
changing a dict’s size while looping RuntimeError: dictionary changed size during iteration loop over list(d)
x in big_list in a loop O(n²) total, slow convert to a set once
xs.pop(0) / insert(0, x) in a loop O(n) each deque.popleft() / appendleft()
{} an empty dict set() for an empty set
set order changes between runs for strings sorted(s) before printing or comparing
unhashable key TypeError: unhashable type: 'list' tuple(xs) or frozenset(s)
d[key] on a missing key KeyError d.get(key), defaultdict, or in check
reading a defaultdict silently adds the key use in or .get() to check
dict(zip(a, b)) with different lengths extra items dropped zip(a, b, strict=True)
a generator used twice the second pass is empty make a list, or create the generator again
Counter.subtract can leave 0 and negative counts +counter drops them
t = ([1],) the tuple is immutable, the list is not; hash(t) fails use only immutable items in keys
list.remove(x) removes only the first x [y for y in xs if y != x]
sorted(d) sorts the keys, not the items sorted(d.items(), key=...)