Python lists and dictionaries cheat sheet
Examples that use ; run left to right, and the result shown is the value of the last part. Methods such as append() and sort() change the list in place and return None, which is why those examples end by showing the list itself. Lessons: lists, dictionaries, comprehensions.
Lists: add and removeLists: order, copy, searchLists: build and combineDicts: read and testDicts: change and build
Lists: add and remove
| Syntax | What it does | Example → result |
|---|---|---|
lst.append(x) | Add one item at the end | a = [1, 2]; a.append(3); a→ [1, 2, 3] |
lst.extend(iterable) | Add every item from an iterable | a = [1]; a.extend([2, 3]); a→ [1, 2, 3] |
lst.insert(i, x) | Insert before position i | a = ["b"]; a.insert(0, "a"); a→ ['a', 'b'] |
lst.remove(x) | Remove the first item equal to x | a = [1, 2, 1]; a.remove(1); a→ [2, 1] |
lst.pop() | Remove and return the last item | a = [1, 2, 3]; a.pop()→ 3 |
lst.pop(i) | Remove and return the item at i | a = [1, 2, 3]; a.pop(0)→ 1 |
del lst[i] | Delete by position or slice | a = [1, 2, 3]; del a[0]; a→ [2, 3] |
lst.clear() | Remove everything | a = [1, 2]; a.clear(); a→ [] |
Lists: order, copy, search
| Syntax | What it does | Example → result |
|---|---|---|
lst.sort() | Sort in place (returns None) | a = [3, 1, 2]; a.sort(); a→ [1, 2, 3] |
lst.sort(key=, reverse=) | Sort by a key function, optionally descending | a = ["bb", "a"]; a.sort(key=len, reverse=True); a→ ['bb', 'a'] |
sorted(iterable) | New sorted list from any iterable | sorted("cab")→ ['a', 'b', 'c'] |
lst.reverse() | Reverse in place | a = [1, 2]; a.reverse(); a→ [2, 1] |
lst.copy() | Shallow copy | a = [1]; b = a.copy(); b.append(2); a→ [1] |
lst.index(x) | Position of the first x (ValueError if absent) | ["x", "y"].index("y")→ 1 |
lst.count(x) | How many items equal x | [1, 1, 2].count(1)→ 2 |
lst[a:b] | Slice from a up to, not including, b | [0, 1, 2, 3][1:3]→ [1, 2] |
lst[::step] | Every step-th item | [0, 1, 2, 3, 4][::2]→ [0, 2, 4] |
x in lst | Membership test | 2 in [1, 2]→ True |
Lists: build and combine
| Syntax | What it does | Example → result |
|---|---|---|
sum(), min(), max(), len() | Aggregate built-ins | sum([1, 2, 3])→ 6 |
enumerate(iterable) | Pairs of (index, item) | list(enumerate("ab"))→ [(0, 'a'), (1, 'b')] |
zip(a, b) | Pairs of items from several iterables | list(zip([1, 2], "ab"))→ [(1, 'a'), (2, 'b')] |
list comprehension | Build a list from an expression | [n * 2 for n in range(3)]→ [0, 2, 4] |
a + b | Concatenate into a new list | [1] + [2, 3]→ [1, 2, 3] |
Dicts: read and test
| Syntax | What it does | Example → result |
|---|---|---|
d[key] | Value for key (KeyError if missing) | {"a": 1}["a"]→ 1 |
d.get(key, default) | Value, or default when missing | {"a": 1}.get("b", 0)→ 0 |
key in d | Is the key present? | "a" in {"a": 1}→ True |
d.keys() | View of the keys | list({"a": 1, "b": 2}.keys())→ ['a', 'b'] |
d.values() | View of the values | list({"a": 1, "b": 2}.values())→ [1, 2] |
d.items() | View of (key, value) pairs | list({"a": 1}.items())→ [('a', 1)] |
len(d) | Number of keys | len({"a": 1, "b": 2})→ 2 |
Dicts: change and build
| Syntax | What it does | Example → result |
|---|---|---|
d[key] = value | Add or replace a key | d = {}; d["x"] = 1; d→ {'x': 1} |
d.setdefault(key, v) | Return the value, inserting v first if missing | d = {}; d.setdefault("n", []).append(1); d→ {'n': [1]} |
d.update(other) | Copy keys from another dict or keyword arguments | d = {"a": 1}; d.update(b=2); d→ {'a': 1, 'b': 2} |
d.pop(key) | Remove a key and return its value | d = {"a": 1, "b": 2}; d.pop("a")→ 1 |
d.popitem() | Remove and return the last inserted pair | d = {"a": 1, "b": 2}; d.popitem()→ ('b', 2) |
del d[key] | Delete a key | d = {"a": 1, "b": 2}; del d["a"]; d→ {'b': 2} |
d1 | d2 | Merge into a new dict (Python 3.9+) | {"a": 1} | {"b": 2}→ {'a': 1, 'b': 2} |
dict.fromkeys(keys, v) | New dict with every key set to v | dict.fromkeys(["x", "y"], 0)→ {'x': 0, 'y': 0} |
dict comprehension | Build a dict from an expression | {n: n * n for n in range(3)}→ {0: 0, 1: 1, 2: 4} |
sorted(d.items(), key=...) | Pairs sorted by value | sorted({"a": 3, "b": 1}.items(), key=lambda kv: kv[1])→ [('b', 1), ('a', 3)] |