04. Data structures — Cheat sheet
The essentials of module 04 on one page. Every runnable block on this page is checked against its output.
Quick lookup
Section titled “Quick lookup”| 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 allowedreadings.append(22.1) # [..., 22.1]readings.insert(0, 20.9) # put 20.9 at index 0last = 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 indexprint(readings, last)print(readings[0], readings[-1], readings[1:3], readings[::-1]) # index, slice, reverseprint(len(readings), sum(readings), min(readings), max(readings))print(21.7 in readings, readings.count(22.0), readings.index(21.7))[20.9, 22.0, 21.9, 21.7] 22.120.9 21.7 [22.0, 21.9] [21.7, 21.9, 22.0, 20.9]4 86.5 20.9 22.0True 1 3| Method | Returns | Changes the list | Cost |
|---|---|---|---|
append(x) |
None |
yes | amortized (on average over many calls) |
extend(items) |
None |
yes | for k items |
insert(i, x) |
None |
yes | |
pop() / pop(i) |
the element | yes | / |
remove(x) |
None |
yes | |
sort() / reverse() |
None |
yes | / |
index(x) / count(x) |
int |
no | |
copy() |
a shallow copy | no | |
sorted(lst) |
a new list | no |
grid = [[0] * 3 for _ in range(2)] # 2 rows x 3 columns, separate rowsgrid[0][1] = 5print(grid)print([*readings, 23.0], readings + [23.0], [0] * 3) # spread, concatenate, repeat[[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]Tuples
Section titled “Tuples”row = ("2024-05-01T00:40:00", "S2", 38.03, "warn") # immutable recordprint(row[1], len(row), row.count("warn"), row.index(38.03))single, empty = ("S1",), () # the comma makes the one-element tupleno_parens = "S1", 20.21 # commas alone make a tupleprint(type(single), len(empty), no_parens)print(("S1", 20.21) < ("S1", 22.3), ("S2", 0.0) > ("S1", 99.0)) # compare left to rightS2 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), ...]) |
Unpacking
Section titled “Unpacking”sensor, temp, status = ("S1", 20.21, "ok") # count must matchfirst, *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] # nestedprint(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)S1 20.21 20.9 [21.9, 21.4] 22.0 S2 00 [20.21, 20.22]1 S1 20.212 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 overwriteprint(customer["plan"], customer.get("phone"), customer.get("phone", "none"))print("plan" in customer, "basic" in customer) # in tests KEYSprint(list(customer.keys())[:2], list(customer.values())[-1])plan = customer.pop("plan") # remove and returnprint(plan, customer.pop("email", None), len(customer))for key, value in customer.items(): print(f"{key}={value}", end=" ")print()basic None noneTrue False['customer_id', 'name'] 72basic None 3customer_id=C00017 name=Mateo Lopez tenure_months=72| Operation | Does | Cost |
|---|---|---|
d[k] / d[k] = v |
read (KeyError if absent) / write | |
d.get(k, default) |
read, default if absent |
|
k in d |
key exists? | |
d.pop(k[, default]) / del d[k] |
remove | |
d.setdefault(k, v) |
insert v if absent, return d[k] |
|
d.update(other) / d |= other |
merge into d |
|
d1 | d2 |
new merged dict | |
d.keys(), d.values(), d.items() |
live views; keys() supports &, |, - |
|
dict(pairs), dict(zip(keys, values)) |
build from pairs | |
dict.fromkeys(keys, value) |
every key gets the same value |
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) # groupdefaults = {"format": "csv", "overwrite": False}print(counts, groups)print(defaults | {"overwrite": True}, defaults.keys() & {"format", "dir"}){'ok': 2, 'warn': 1, 'fail': 1} {'S1': ['ok', 'ok'], 'S2': ['warn', 'fail']}{'format': 'csv', 'overwrite': True} {'format'}sold = set(["P001", "P014", "P001", "P017"]) # duplicates vanishsold.add("P021")sold.discard("P999") # no error if absent; remove() raises KeyErrorchicago = {"P015", "P017", "P019", "P020", "P030"} # S01, 2024-06-01denver = {"P020", "P024", "P027"} # S12, 2024-06-01print(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"}))['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 |
Nested data and JSON
Section titled “Nested data and JSON”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"))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 |
| 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 -> columnsrecords = [dict(zip(columns, vals)) for vals in zip(*columns.values())] # and backlookup = {r["customer_id"]: r for r in customers} # records -> lookupprint(columns["plan"][:3], records[1], lookup["C00002"]["plan"])['premium', 'standard', 'premium'] {'customer_id': 'C00002', 'plan': 'standard'} standardMutability, aliasing and copies
Section titled “Mutability, aliasing and copies”import copy
a = [21.0, 21.9]b = a # alias: same objectb.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"])[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 |
Comprehensions
Section titled “Comprehensions”raw = ["21.0", "error", "21.9", "", "22.6"]values = [float(t) for t in raw if t.replace(".", "", 1).isdigit()] # filter at the endlabels = ["high" if v > 22.5 else "ok" for v in values] # choose at the frontsquares = {v: round(v * v, 1) for v in values} # dictplans = {c["plan"] for c in customers} # setamounts = [o["amount"] for c in customers[:2] for o in c["orders"]] # flattenprint(values, labels, squares, sorted(plans), len(amounts), sep="\n")[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] |
Big-O and the right structure
Section titled “Big-O and the right structure”| Operation | list |
tuple |
dict |
set |
|---|---|---|---|---|
x in c |
(keys) | |||
get by position c[i] |
— | — | ||
get by key d[k] |
— | — | — | |
| add at the end / add | — | |||
| insert or remove at the front | — | — | — | |
| remove a given value | — | by key | ||
| sort | via sorted() |
via sorted() |
via sorted() |
append is amortized: on average over many calls, because the list sometimes grows its storage. Set and dict lookups are 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)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) |
Gotchas
Section titled “Gotchas”b = anever copies. Usea.copy()for flat data andcopy.deepcopy(a)for nested data.- A shallow copy shares the nested lists and dicts.
list(records)andrecords[:]do not copy the records. lst.sort(),lst.append(),lst.extend(),d.update()ands.add()returnNone. 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.inon a dict tests the keys, not the values.d[key]raisesKeyErrorfor a missing key.d.get(key)returnsNone, andNonealso comes back for a key whose value isNone.- 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
frozensetas a key. [[0] * 3] * 3repeats 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_listinside 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.