Skip to content

04. Data structures — Cheat sheet

The essentials of module 04 on one page. Every runnable block on this page is checked against its output.

I want to… Use… Example
keep values in order list readings = [21.0, 21.9, 21.4]
add one value at the end lst.append(x) readings.append(22.1)
add many values at the end lst.extend(items) or lst += items readings.extend([22.0, 22.5])
get a sorted copy sorted(lst) sorted(readings, reverse=True)[:3]
sort in place lst.sort() (returns None) readings.sort()
store a fixed record tuple row = ("S1", 20.21, "ok")
make a one-element tuple a trailing comma ("S1",)
give each field a name unpacking sensor, temp, status = row
take the first and the rest star-unpacking header, *rows = lines
swap two values tuple unpacking low, high = high, low
look up a value by key dict price_of["P001"]
read an optional key d.get(key, default) c.get("phone", "none")
count occurrences d[k] = d.get(k, 0) + 1 counts[plan] = counts.get(plan, 0) + 1
group values by key d.setdefault(k, []).append(x) by_sensor.setdefault(s, []).append(t)
merge two dicts d1 | d2 (right side wins) settings = defaults | user
keep unique values set set(product_ids)
test membership fast x in my_set "P014" in sold
values in both / either / only one &, |, -, ^ chicago & denver
start an empty set set() (not {}) seen = set()
drop duplicates, keep order list(dict.fromkeys(items)) list(dict.fromkeys(cities))
build a list from another list comprehension [round(c * 9 / 5 + 32, 1) for c in readings]
build a dict from another dict comprehension {c["customer_id"]: c for c in customers}
build a set from another set comprehension {c["plan"] for c in customers}
copy a flat list or dict .copy() backup = readings.copy()
copy nested records copy.deepcopy(x) shared = copy.deepcopy(customers)
check “same object?” is backup is readings
load a JSON file json.load(f) see Nested data
readings = [21.0, 21.9, 21.4, 21.7] # ordered, mutable, duplicates allowed
readings.append(22.1) # [..., 22.1]
readings.insert(0, 20.9) # put 20.9 at index 0
last = readings.pop() # remove and return the last element (22.1)
readings.remove(21.4) # remove the first 21.4 (ValueError if absent)
readings[1] = 22.0 # replace by index
print(readings, last)
print(readings[0], readings[-1], readings[1:3], readings[::-1]) # index, slice, reverse
print(len(readings), sum(readings), min(readings), max(readings))
print(21.7 in readings, readings.count(22.0), readings.index(21.7))
Output
[20.9, 22.0, 21.9, 21.7] 22.1
20.9 21.7 [22.0, 21.9] [21.7, 21.9, 22.0, 20.9]
4 86.5 20.9 22.0
True 1 3
Method Returns Changes the list Cost
append(x) None yes O(1)O(1) amortized (on average over many calls)
extend(items) None yes O(k)O(k) for k items
insert(i, x) None yes O(n)O(n)
pop() / pop(i) the element yes O(1)O(1) / O(n)O(n)
remove(x) None yes O(n)O(n)
sort() / reverse() None yes O(nlog⁡n)O(n \log n) / O(n)O(n)
index(x) / count(x) int no O(n)O(n)
copy() a shallow copy no O(n)O(n)
sorted(lst) a new list no O(nlog⁡n)O(n \log n)
grid = [[0] * 3 for _ in range(2)] # 2 rows x 3 columns, separate rows
grid[0][1] = 5
print(grid)
print([*readings, 23.0], readings + [23.0], [0] * 3) # spread, concatenate, repeat
Output
[[0, 5, 0], [0, 0, 0]]
[20.9, 22.0, 21.9, 21.7, 23.0] [20.9, 22.0, 21.9, 21.7, 23.0] [0, 0, 0]
row = ("2024-05-01T00:40:00", "S2", 38.03, "warn") # immutable record
print(row[1], len(row), row.count("warn"), row.index(38.03))
single, empty = ("S1",), () # the comma makes the one-element tuple
no_parens = "S1", 20.21 # commas alone make a tuple
print(type(single), len(empty), no_parens)
print(("S1", 20.21) < ("S1", 22.3), ("S2", 0.0) > ("S1", 99.0)) # compare left to right
Output
S2 4 1 2
<class 'tuple'> 0 ('S1', 20.21)
True True
Use a tuple for Example
a fixed record ("S1", 20.21, "ok")
a dict key with several parts totals[("S1", "00")]
an element of a set {(41.88, -87.63)}
several return values of a function return low, high (module 05)
sorting by several fields sorted([(total, cid), ...])
sensor, temp, status = ("S1", 20.21, "ok") # count must match
first, *middle, last = [20.9, 21.9, 21.4, 22.0] # *name always gets a list
_, sensor_id, *_ = row # _ = "I do not need this"
(sensor, hour), temps = ("S1", "00"), [20.21, 20.22] # nested
print(sensor, temp, first, middle, last, sensor_id, hour, temps)
for i, (s, t) in enumerate([("S1", 20.21), ("S2", 22.3)], start=1):
print(i, s, t)
Output
S1 20.21 20.9 [21.9, 21.4] 22.0 S2 00 [20.21, 20.22]
1 S1 20.21
2 S2 22.3
Pattern Meaning
a, b = b, a swap
head, *tail = items first element and the rest
*init, last = items everything but the last, and the last
[*a, *b], (*a, *b), {*a, *b} spread into a new list, tuple or set
{**d1, **d2} spread into a new dict (right side wins)
f(*args) / f(**kwargs) spread into function arguments (module 05)
zip(*rows) transpose rows into columns
customer = {"customer_id": "C00017", "name": "Mateo Lopez", "plan": "basic"}
customer["tenure_months"] = 72 # add or overwrite
print(customer["plan"], customer.get("phone"), customer.get("phone", "none"))
print("plan" in customer, "basic" in customer) # in tests KEYS
print(list(customer.keys())[:2], list(customer.values())[-1])
plan = customer.pop("plan") # remove and return
print(plan, customer.pop("email", None), len(customer))
for key, value in customer.items():
print(f"{key}={value}", end=" ")
print()
Output
basic None none
True False
['customer_id', 'name'] 72
basic None 3
customer_id=C00017 name=Mateo Lopez tenure_months=72
Operation Does Cost
d[k] / d[k] = v read (KeyError if absent) / write O(1)O(1)
d.get(k, default) read, default if absent O(1)O(1)
k in d key exists? O(1)O(1)
d.pop(k[, default]) / del d[k] remove O(1)O(1)
d.setdefault(k, v) insert v if absent, return d[k] O(1)O(1)
d.update(other) / d |= other merge into d O(k)O(k)
d1 | d2 new merged dict O(n+k)O(n + k)
d.keys(), d.values(), d.items() live views; keys() supports &, |, - O(1)O(1)
dict(pairs), dict(zip(keys, values)) build from pairs O(n)O(n)
dict.fromkeys(keys, value) every key gets the same value O(n)O(n)
counts, groups = {}, {}
for sensor, status in [("S1", "ok"), ("S2", "warn"), ("S1", "ok"), ("S2", "fail")]:
counts[status] = counts.get(status, 0) + 1 # count
groups.setdefault(sensor, []).append(status) # group
defaults = {"format": "csv", "overwrite": False}
print(counts, groups)
print(defaults | {"overwrite": True}, defaults.keys() & {"format", "dir"})
Output
{'ok': 2, 'warn': 1, 'fail': 1} {'S1': ['ok', 'ok'], 'S2': ['warn', 'fail']}
{'format': 'csv', 'overwrite': True} {'format'}
sold = set(["P001", "P014", "P001", "P017"]) # duplicates vanish
sold.add("P021")
sold.discard("P999") # no error if absent; remove() raises KeyError
chicago = {"P015", "P017", "P019", "P020", "P030"} # S01, 2024-06-01
denver = {"P020", "P024", "P027"} # S12, 2024-06-01
print(sorted(sold), len(sold), "P014" in sold)
print(sorted(chicago | denver), sorted(chicago & denver))
print(sorted(chicago - denver), sorted(chicago ^ denver))
print({"P020"} <= denver, chicago.isdisjoint({"P001"}), frozenset({"vip"}))
Output
['P001', 'P014', 'P017', 'P021'] 4 True
['P015', 'P017', 'P019', 'P020', 'P024', 'P027', 'P030'] ['P020']
['P015', 'P017', 'P019', 'P030'] ['P015', 'P017', 'P019', 'P024', 'P027', 'P030']
True True frozenset({'vip'})
Operator Method Meaning
a | b a.union(b) in either
a & b a.intersection(b) in both
a - b a.difference(b) in a only
a ^ b a.symmetric_difference(b) in exactly one
a <= b a.issubset(b) every element of a is in b
a < b proper subset: a <= b and a != b
a >= b a.issuperset(b) every element of b is in a
a.isdisjoint(b) no common element
a |= b, a &= b, a -= b a.update(b), … change a in place
import json
with open("data/customers.json", encoding="utf-8") as f: # module 07 explains files
customers = json.load(f)["customers"]
c = customers[0]
print(c["address"]["city"], c["tags"][0], c["orders"][-1]["amount"])
print(c.get("phone"), c["address"].get("postal_code", "missing"))
Output
Chicago mobile_app 24.5
+1-555-908-5284 81790
JSON Python
object {"a": 1} dict
array [1, 2] list
string "x" str
number 1, 1.5 int, float
true, false True, False
null None
Shape Looks like Best for
records [{"id": 1, "plan": "basic"}, ...] rows, JSON, APIs
columns {"id": [1, 2], "plan": ["basic", "premium"]} column math, pd.DataFrame
lookup {"C00001": {...}, "C00002": {...}} find by id in O(1)O(1)
long table [("C00001", "O000614", 32.0), ...] one tuple per fact; filter and sum
fields = ["customer_id", "plan"]
columns = {f: [r[f] for r in customers] for f in fields} # records -> columns
records = [dict(zip(columns, vals)) for vals in zip(*columns.values())] # and back
lookup = {r["customer_id"]: r for r in customers} # records -> lookup
print(columns["plan"][:3], records[1], lookup["C00002"]["plan"])
Output
['premium', 'standard', 'premium'] {'customer_id': 'C00002', 'plan': 'standard'} standard
import copy
a = [21.0, 21.9]
b = a # alias: same object
b.append(22.1)
print(a, b is a, a == [21.0, 21.9, 22.1]) # is = same object, == = equal values
record = {"name": "Ana Silva", "address": {"city": "Chicago"}}
shallow, deep = record.copy(), copy.deepcopy(record)
shallow["address"]["city"] = "Denver" # shared nested dict!
print(record["address"], deep["address"], shallow["address"] is record["address"])
Output
[21.0, 21.9, 22.1] True True
{'city': 'Denver'} {'city': 'Chicago'} True
Type Mutable Hashable (dict key, set element)
int, float, bool, str, None no yes
tuple no yes, if its elements are
frozenset no yes
list, dict, set yes no
Copy How Copies nested objects
none (alias) b = a no, and not the outer one either
shallow a.copy(), list(a), a[:], dict(d), copy.copy(a) no
deep copy.deepcopy(a) yes, every level
new structure a comprehension that builds new objects as deep as you write it
raw = ["21.0", "error", "21.9", "", "22.6"]
values = [float(t) for t in raw if t.replace(".", "", 1).isdigit()] # filter at the end
labels = ["high" if v > 22.5 else "ok" for v in values] # choose at the front
squares = {v: round(v * v, 1) for v in values} # dict
plans = {c["plan"] for c in customers} # set
amounts = [o["amount"] for c in customers[:2] for o in c["orders"]] # flatten
print(values, labels, squares, sorted(plans), len(amounts), sep="\n")
Output
[21.0, 21.9, 22.6]
['ok', 'ok', 'high']
{21.0: 441.0, 21.9: 479.6, 22.6: 510.8}
['basic', 'premium', 'standard']
8
Kind Syntax
list [expr for x in items if cond]
set {expr for x in items if cond}
dict {k: v for x in items if cond}
generator expression (lazy, module 10) sum(expr for x in items)
two loops [expr for a in outer for b in a]: same order as nested loops
choose a value [a if cond else b for x in items]
Operation list tuple dict set
x in c O(n)O(n) O(n)O(n) O(1)O(1) (keys) O(1)O(1)
get by position c[i] O(1)O(1) O(1)O(1) — —
get by key d[k] — — O(1)O(1) —
add at the end / add O(1)O(1) — O(1)O(1) O(1)O(1)
insert or remove at the front O(n)O(n) — — —
remove a given value O(n)O(n) — O(1)O(1) by key O(1)O(1)
sort O(nlog⁡n)O(n \log n) via sorted() via sorted() via sorted()

append is O(1)O(1) amortized: on average over many calls, because the list sometimes grows its storage. Set and dict lookups are O(1)O(1) on average and can slow down when many hashes collide.

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=500)
t_set = timeit.timeit('"C05000" in id_set', globals=globals(), number=500)
print("set at least 100x faster:", t_set * 100 < t_list)
Output
set at least 100x faster: True
Your main question Choose
“What is at position i?” or “keep this order” list
“Is this record fixed?” or “I need a compound key” tuple
“What is the value for this id?” dict
“How many of each?” dict of counts (Counter, module 09)
“Have I seen this before?” or “unique values” set
“Which are in both groups?” two sets and &
“Unique, but keep the first-seen order” dict.fromkeys(items)
“Millions of numbers, math on whole columns” NumPy array or pandas column (module 23)
  • b = a never copies. Use a.copy() for flat data and copy.deepcopy(a) for nested data.
  • A shallow copy shares the nested lists and dicts. list(records) and records[:] do not copy the records.
  • lst.sort(), lst.append(), lst.extend(), d.update() and s.add() return None. Do not assign their result.
  • append([a, b]) adds one element, a list. extend([a, b]) adds two.
  • ("S1") is a string. ("S1",) is a tuple.
  • {} is an empty dict. set() is an empty set.
  • in on a dict tests the keys, not the values.
  • d[key] raises KeyError for a missing key. d.get(key) returns None, and None also comes back for a key whose value is None.
  • A set of strings prints in a different order in different runs. Print sorted(s).
  • Lists, dicts and sets are unhashable. Use a tuple or a frozenset as a key.
  • [[0] * 3] * 3 repeats one inner list three times. Use [[0] * 3 for _ in range(3)].
  • Removing from a list while you loop over it skips elements. Adding keys to a dict while you loop over it raises RuntimeError.
  • In a dict comprehension, a repeated key silently keeps the last value.
  • x in big_list inside a loop is quadratic. Convert the list to a set once, before the loop.
  • += on a list changes it in place (aliases see it). += on a tuple or a string makes a new object.