This page covers the Python a script needs every day: how names refer to objects, which built-in container to reach for, how branches and loops decide what runs, and how functions and comprehensions are written. Examples use operations data such as HTTP status codes.
Names point at objects
A Python name is a label pointing at an object, not a box holding a value. Assigning one name to another copies the pointer, so both names share one object, and a change made through one is visible through the other when the object is mutable.
first = [1, 2]
second = first
second.append(3) # first is now [1, 2, 3]== compares values and is compares identity; write value is None. The immutable basics are int, float, bool, str, tuple, and frozenset; the mutable ones are list, dict, and set.1 Every string method returns a new string, since strings are immutable.2
Sharing causes three classic bugs:
[[0] * 3] * 2creates two references to one inner list; build rows with[[0] * 3 for _ in range(2)].copy()is shallow, so nested objects stay shared.3- Default arguments are evaluated once, when the function is defined, so a mutable default is shared by every call. Default to
Noneand create the object inside.4
Choosing a collection
Pick the container whose order, mutability, and uniqueness match the data.5
| Type | Ordered | Mutable | Use |
|---|---|---|---|
list | Yes | Yes | A resizable sequence |
tuple | Yes | No | Fixed records and multiple return values; one item needs (10,) |
dict | Insertion order | Yes | Hashable keys mapped to values |
set | No | Yes | Unique hashable values; set() for empty, since {} is a dict |
str | Yes | No | Text |
As described in the cheatsheets.362
Working with lists, dicts, sets, and strings
- Lists. Mutating methods (
sort,append,remove) change the list and returnNone;sorted()andcopy()build new lists.remove()raisesValueErrorfor a missing value and indexing past the end raisesIndexError, while slices stop quietly at the boundary.3 - Dictionaries. Use
mapping[key]when a missing key is an error andget()orsetdefault()when a default is valid.a | bmerges (Python 3.9+). Equality ignores insertion order.6 - Sets.
|,&,-, and^give union, intersection, difference, and symmetric difference;discard()does not raise when the value is absent.5 - Strings.
split()with no argument splits on any whitespace," | ".join(parts)joins,f"{service=}"prints a name with its value, and raw strings such asr"\d+"keep backslashes literal.2
Branches
An if/elif/else chain runs exactly one branch: the first true condition wins and later ones are never evaluated.
flowchart TD accTitle: if, elif, else branch selection accDescr: Python checks conditions in order and runs only the first branch whose condition is true, falling through to else when none match. A{if condition true?} -- Yes --> RA[Run if block] A -- No --> B{elif condition true?} B -- Yes --> RB[Run elif block] B -- No --> C[Run else block] RA --> D[Continue] RB --> D C --> D
Empty strings and collections, zero, and None are false. Comparisons chain (500 <= status < 600), and and/or short-circuit with precedence not, and, or. A common bug is status == 200 or 201, which is always true; write status in (200, 201). match (Python 3.10+) matches structure with case _ as the fallback, but plain if is clearer for one or two conditions.7
Loops
Iterate over values directly, with enumerate when you need indexes and zip(..., strict=True) (Python 3.10+) to catch inputs of different lengths. range excludes its stop value. A loop’s else block runs only when the loop ends without break, which makes it a natural “not found” branch for a search. Never modify a list while iterating over it; build a new one.8
Functions
A signature is a contract: positional parameters, keyword-only parameters after *, *args, **kwargs, and defaults each control how callers pass arguments. A function that reaches its end without return returns None.4
def connect(host: str, port: int = 443, *, timeout: float = 5.0) -> str: ...Comprehensions
A comprehension is a loop written as an expression, [expression for item in iterable if condition], and its brackets pick the result: [] a list, {} a set or dict, () a lazy generator expression. Nested comprehensions read in the same order as nested for loops; switch to a plain loop when nesting or conditions make one hard to scan.9 Laziness is covered under generators.