TetSharing

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

SyntaxWhat it doesExample → result
lst.append(x)Add one item at the enda = [1, 2]; a.append(3); a
→ [1, 2, 3]
lst.extend(iterable)Add every item from an iterablea = [1]; a.extend([2, 3]); a
→ [1, 2, 3]
lst.insert(i, x)Insert before position ia = ["b"]; a.insert(0, "a"); a
→ ['a', 'b']
lst.remove(x)Remove the first item equal to xa = [1, 2, 1]; a.remove(1); a
→ [2, 1]
lst.pop()Remove and return the last itema = [1, 2, 3]; a.pop()
→ 3
lst.pop(i)Remove and return the item at ia = [1, 2, 3]; a.pop(0)
→ 1
del lst[i]Delete by position or slicea = [1, 2, 3]; del a[0]; a
→ [2, 3]
lst.clear()Remove everythinga = [1, 2]; a.clear(); a
→ []

Lists: order, copy, search

SyntaxWhat it doesExample → 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 descendinga = ["bb", "a"]; a.sort(key=len, reverse=True); a
→ ['bb', 'a']
sorted(iterable)New sorted list from any iterablesorted("cab")
→ ['a', 'b', 'c']
lst.reverse()Reverse in placea = [1, 2]; a.reverse(); a
→ [2, 1]
lst.copy()Shallow copya = [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 lstMembership test2 in [1, 2]
→ True

Lists: build and combine

SyntaxWhat it doesExample → result
sum(), min(), max(), len()Aggregate built-inssum([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 iterableslist(zip([1, 2], "ab"))
→ [(1, 'a'), (2, 'b')]
list comprehensionBuild a list from an expression[n * 2 for n in range(3)]
→ [0, 2, 4]
a + bConcatenate into a new list[1] + [2, 3]
→ [1, 2, 3]

Dicts: read and test

SyntaxWhat it doesExample → 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 dIs the key present?"a" in {"a": 1}
→ True
d.keys()View of the keyslist({"a": 1, "b": 2}.keys())
→ ['a', 'b']
d.values()View of the valueslist({"a": 1, "b": 2}.values())
→ [1, 2]
d.items()View of (key, value) pairslist({"a": 1}.items())
→ [('a', 1)]
len(d)Number of keyslen({"a": 1, "b": 2})
→ 2

Dicts: change and build

SyntaxWhat it doesExample → result
d[key] = valueAdd or replace a keyd = {}; d["x"] = 1; d
→ {'x': 1}
d.setdefault(key, v)Return the value, inserting v first if missingd = {}; d.setdefault("n", []).append(1); d
→ {'n': [1]}
d.update(other)Copy keys from another dict or keyword argumentsd = {"a": 1}; d.update(b=2); d
→ {'a': 1, 'b': 2}
d.pop(key)Remove a key and return its valued = {"a": 1, "b": 2}; d.pop("a")
→ 1
d.popitem()Remove and return the last inserted paird = {"a": 1, "b": 2}; d.popitem()
→ ('b', 2)
del d[key]Delete a keyd = {"a": 1, "b": 2}; del d["a"]; d
→ {'b': 2}
d1 | d2Merge 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 vdict.fromkeys(["x", "y"], 0)
→ {'x': 0, 'y': 0}
dict comprehensionBuild 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 valuesorted({"a": 3, "b": 1}.items(), key=lambda kv: kv[1])
→ [('b', 1), ('a', 3)]

Official docs

Compiled by Ethan Cole (pen name) with AI-assisted drafting; every example in the table is executed by our test suite. Related lessons: lists, dictionaries, list comprehensions.