SchoolWhool
Quizzes and saved progress, freeSign in freeSign in
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

videoterms
3.1an 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.2a 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.3a 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.4a 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.5a string is an immutable sequence of characters · chaining calls a method on the last method's result · tokenisation splits text into tokens
3.6a list comprehension, set comprehension or dictionary comprehension builds a collection from an expression for each item

Which structure

list [...]tuple (...)set {...}dictionary {k: v}
orderedyesyesnoinsertion order
changeableyesnoyesyes
duplicatesyesyesnokeys no, values yes
read byindexindex, or unpackingin onlykey
empty[]()set(){}
use it fora sequence that grows or is editeda fixed group where each position means somethingunique values, fast in, comparing groupslooking up a value by a name

Syntax at a glance

With week = [8200, 10450, 6300, 12000, 9100, 7400, 11050]:

writegivesnote
week[0] · week[-1] · week[3]8200 · 11050 · 12000index 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 itselfappend 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.9716the number of names must match
("Asha",) · ("Asha")a tuple · a strthe comma makes the tuple
set(["asha", "ravi", "asha"]) · len(...)two names · 2show a set of strings with sorted(...)
a | b · a & b · a - b · a ^ bunion · intersection · difference · in exactly one
menu["Soup"] · menu.get("Pizza", 0.0)6.0 · 0.0menu["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 valuefor item in menu: gives the keys
counts[w] = counts.get(w, 0) + 1counting by handCounter(words), .most_common(5)
groups = defaultdict(list) · groups[k].append(v)groupingfrom collections import defaultdict
s.strip() · s.lower() · s.replace(",", "") · s.split() · " ".join(words)strings, or a list from splita string never changes; assign the result
s.find("fast") · s.count("e") · "fast" in sposition 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 0 to len - 1, and from -1 back to -len. An index past the end is an IndexError; 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, remove and sort return None; pop returns the removed element. Never write x = 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; sorted gives a list in a fixed order.
  • Set members and dictionary keys must be hashable: numbers, strings, tuples of those. Not lists, sets or dictionaries.
  • in on a list compares item by item; in on a set or dictionary uses the hash and equality checks, with roughly constant lookup time on average; collisions can require extra checks.
  • in on 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 defaultdict adds it. Test with in.
  • Text methods return strings; an unchanged string may be reused, and split returns a list. review.lower() alone changes nothing.
  • find returns -1 when it finds nothing, and -1 is a valid index.
  • A comprehension is for building a value. For printing, several steps per item, or break, write the loop.

Common mistakes

mistakewhat you seefix
week[7] on seven elementsIndexError: list index out of rangethe last index is len(week) - 1, or use week[-1]
cart.remove("tea") when it is not thereValueError: list.remove(x): x not in listcheck with in first
prices = prices.sort()prices is Noneprices.sort() on its own, or sorted(prices)
backup = cart as a backupthe backup changes with the cartcart.copy()
point[0] = 13.0 on a tupleTypeError: 'tuple' object does not support item assignmentbuild 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 settype({}) is <class 'dict'>set()
unique[0] on a setTypeError: 'set' object is not subscriptablesorted(unique)[0]
a list in a set or as a keyTypeError: unhashable type: 'list'a tuple
menu["Pizza"]KeyError: 'Pizza'menu.get("Pizza", 0.0)
counts[w] += 1 on a new keyKeyErrorcounts.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 foundconvert 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]