Lists are ordered and mutable; dictionaries are ordered (3.7+) key-value maps. Comprehensions build new lists/dicts. Use .get(key, default) instead of d[key] when missing keys are normal. Copy with list.copy() / {**d} — assignment copies the reference, not the contents.
This Python cheat sheet is written for people searching for a fast, accurate reference: students, junior developers, and teams shipping production software. Pin it, copy the snippets, and come back when syntax slips.
Quick reference
- List ops:
append,extend,pop,insert, slicing assignment. - Sort:
sorted(xs)new list.xs.sort()in place.key=andreverse=True. - Dict get:
d.get("email")→Noneif missing.d["email"]raisesKeyError. - Merge:
{**a, **b}ora | b(3.9+). Later keys win. - Comp:
[x for x in xs if x],{k: v.upper() for k, v in d.items()}. - Unpack:
for i, v in enumerate(xs, start=1):,for k, v in d.items():. - in:
x in xsscans a list (O(n)).k in dis a key check (O(1) average). - Copy:
xs[:]shallow.copy.deepcopyfor nested structures.
Copy-paste examples
Group and index without mutating while iterating
Build a new dict. Do not del d[k] while looping d without copying keys first.
from collections import defaultdict
def by_city(rows: list[dict]) -> dict[str, list[str]]:
grouped: dict[str, list[str]] = defaultdict(list)
for row in rows:
city = row.get('city') or 'Unknown'
name = row.get('name') or ''
if name:
grouped[city].append(name)
return dict(grouped)
def index_by_id(rows: list[dict]) -> dict[int, dict]:
return {int(r['id']): r for r in rows if 'id' in r}Common mistakes
for x in xs: xs.remove(x)— skipped items because the list shrinks under the iterator.- Using a list as a lookup table for thousands of membership tests (use a
set). dict[key]withoutgetfor optional JSON fields, then crashing on KeyError.- Shallow copy of a list of dicts then mutating inner dicts and surprising the original.
FAQ
- list vs tuple? Tuples are immutable and hashable (if items are). Use tuples for fixed records and dict keys; lists for growing collections.
- dict vs JSON object? JSON objects decode to
dict. Keys becomestr.json.dumpsdoes not support every Python type (datetime, set).
- OrderedDict still needed? Rarely for equality-by-order tricks. Regular dicts keep insertion order since 3.7.
Related Python cheat sheets
Build with this stack
When a cheat sheet is not enough — you need a production app, a student FYP, or a custom dashboard — ArpaNeuro builds custom web development and also sells ready-made source code. Request a quote and tell us the stack.
Browse software development services or the source code marketplace if you want a working codebase instead of starting from a blank file.