Python · Module 3Module material
Python data structures cheat sheet
Lists, tuples, dictionaries and sets on one page: the terms, which structure to use, the syntax at a glance, the rules and the common mistakes. Free to read and share, no account needed.
Terms
| video | terms |
|---|---|
| 3.1 | an element is one value in a list · its index counts from zero · a slice runs from a start up to, not including, a stop · a method is called with a dot · a list is mutable · an alias is a second name for one object · a mutation changes the object, and every alias sees it |
| 3.2 | a tuple is an ordered sequence that can not be changed: it is immutable · packing collects values into a tuple · unpacking binds each item to its own name |
| 3.3 | a set holds each value at most once, in no order · union a | b · intersection a & b · difference a - b · a hash is a number used to choose lookup candidates · only hashable values can be set members or keys |
| 3.4 | a dictionary maps each key to a value; each entry is a key value pair · a nested dictionary has dictionaries as values · Counter counts · defaultdict creates a missing key's value |
| 3.5 | a string is an immutable sequence of characters · chaining calls a method on the last method's result · tokenisation splits text into tokens |
| 3.6 | a list comprehension, set comprehension or dictionary comprehension builds a collection from an expression for each item |
Which structure
list [...] | tuple (...) | set {...} | dictionary {k: v} | |
|---|---|---|---|---|
| ordered | yes | yes | no | insertion order |
| changeable | yes | no | yes | yes |
| duplicates | yes | yes | no | keys no, values yes |
| read by | index | index, or unpacking | in only | key |
| empty | [] | () | set() | {} |
| use it for | a sequence that grows or is edited | a fixed group where each position means something | unique values, fast in, comparing groups | looking up a value by a name |
Syntax at a glance
With week = [8200, 10450, 6300, 12000, 9100, 7400, 11050]:
| write | gives | note |
|---|---|---|
week[0] · week[-1] · week[3] | 8200 · 11050 · 12000 | index from the start, or from the end |
week[-3:] · week[:2] · week[::2] | [9100, 7400, 11050] · [8200, 10450] · [8200, 6300, 9100, 11050] | a slice is a new list; the stop is excluded |
cart.append(x) · cart.insert(i, x) · cart.remove(x) · cart.pop() | change the list itself | append shows nothing; pop returns the element |
sorted(week) · week.sort() | a new sorted list · sorts week, returns None | |
sum(week) · min(week) · max(week) · len(week) | 64500 · 6300 · 12000 · 7 | |
12000 in week · week.index(12000) · [5, 4, 5, 3, 5].count(5) | True · 3 · 3 | |
backup = cart.copy() | a separate outer list (shallow copy) | backup = cart is an alias |
lat, lon = (12.9716, 77.5946) | lat is 12.9716 | the number of names must match |
("Asha",) · ("Asha") | a tuple · a str | the comma makes the tuple |
set(["asha", "ravi", "asha"]) · len(...) | two names · 2 | show a set of strings with sorted(...) |
a | b · a & b · a - b · a ^ b | union · intersection · difference · in exactly one | |
menu["Soup"] · menu.get("Pizza", 0.0) | 6.0 · 0.0 | menu["Pizza"] is a KeyError |
menu["Bread"] = 3.75 · menu.pop("Salad") · del menu["Pasta"] | adds or updates · removes and returns · removes | |
for item, price in menu.items(): | each key with its value | for item in menu: gives the keys |
counts[w] = counts.get(w, 0) + 1 | counting by hand | Counter(words), .most_common(5) |
groups = defaultdict(list) · groups[k].append(v) | grouping | from collections import defaultdict |
s.strip() · s.lower() · s.replace(",", "") · s.split() · " ".join(words) | strings, or a list from split | a string never changes; assign the result |
s.find("fast") · s.count("e") · "fast" in s | position or -1 · a count · a bool | |
[round(p * 1.08, 2) for p in prices] | [13.5, 8.91, 6.48] for [12.50, 8.25, 6.00] | expression, then for, then an optional if |
{item: price for item, price in zip(items, prices)} | a dictionary | {len(i) for i in items} is a set |
Rules
- Indices run from
0tolen - 1, and from-1back to-len. An index past the end is anIndexError; a slice past the end is not. - Assigning to a name rebinds it; assigning to a list item or calling a mutating method changes the object. Every alias sees a mutation. With lists,
x += [...]mutates,x = x + [...]rebinds. append,insert,removeandsortreturnNone;popreturns the removed element. Never writex = x.sort().- A tuple fixes which objects it holds, not what is in them: a list inside a tuple can still be appended to.
- A set has no order and no index. Never rely on how it prints;
sortedgives a list in a fixed order. - Set members and dictionary keys must be hashable: numbers, strings, tuples of those. Not lists, sets or dictionaries.
inon a list compares item by item;inon a set or dictionary uses the hash and equality checks, with roughly constant lookup time on average; collisions can require extra checks.inon a dictionary checks the keys, not the values.- Dictionaries keep insertion order (Python 3.7+);
popitem()removes the last pair added. - Reading a missing key of a
defaultdictadds it. Test within. - Text methods return strings; an unchanged string may be reused, and
splitreturns a list.review.lower()alone changes nothing. findreturns-1when it finds nothing, and-1is a valid index.- A comprehension is for building a value. For printing, several steps per item, or
break, write the loop.
Common mistakes
| mistake | what you see | fix |
|---|---|---|
week[7] on seven elements | IndexError: list index out of range | the last index is len(week) - 1, or use week[-1] |
cart.remove("tea") when it is not there | ValueError: list.remove(x): x not in list | check with in first |
prices = prices.sort() | prices is None | prices.sort() on its own, or sorted(prices) |
backup = cart as a backup | the backup changes with the cart | cart.copy() |
point[0] = 13.0 on a tuple | TypeError: 'tuple' object does not support item assignment | build a new tuple |
lat, lon = (12.9716, 77.5946, 920) | ValueError: too many values to unpack (expected 2) | one name per item |
{} for an empty set | type({}) is <class 'dict'> | set() |
unique[0] on a set | TypeError: 'set' object is not subscriptable | sorted(unique)[0] |
| a list in a set or as a key | TypeError: unhashable type: 'list' | a tuple |
menu["Pizza"] | KeyError: 'Pizza' | menu.get("Pizza", 0.0) |
counts[w] += 1 on a new key | KeyError | counts.get(w, 0) + 1, or Counter |
word[0] = "K" | TypeError: 'str' object does not support item assignment | "K" + word[1:] |
", ".join([12, 8]) | TypeError: sequence item 0: expected str instance, int found | convert to strings first |
[s for s in week if s >= 10000 else 0] | SyntaxError: invalid syntax | [s if s >= 10000 else 0 for s in week] |