Cheatsheets / Python

Python Cheatsheet

Complete Python reference. Hit Ctrl+P to print.

Variables & Types

x = 42Integer - no declaration keyword needed
x = 3.14Float
x = "hello" # or 'hello'String - single and double quotes are equivalent
x = True / FalseBoolean - capitalised
x = NoneNone - absence of a value (like null)
x = [1, 2, 3]List
x = (1, 2, 3)Tuple - immutable list
x = {1, 2, 3}Set - unordered, unique values
x = {"a": 1, "b": 2}Dict
type(x)Returns the type object, e.g.
isinstance(x, int)True if x is an instance of int (or subclass)
int("42") / float("3.14") / str(42)Type conversion
bool(0) / bool("") / bool([])Falsy values: 0, 0.0, "", [], {}, (), None, False
x: int = 42Type annotation (hint only - not enforced at runtime)
a, b, c = 1, 2, 3Multiple assignment / unpacking
a, *rest = [1, 2, 3, 4]Starred unpacking - rest = [2, 3, 4]
x = y = 0Chain assignment

Strings

f"Hello, {name}!"f-string interpolation (preferred, Python 3.6+)
f"{value:.2f}"f-string with format spec - 2 decimal places
"Hello" + " " + "World"Concatenation with +
"ab" * 3Repeat: "ababab"
len(s)Number of characters
s[0] / s[-1]First / last character (negative indexes from end)
s[1:4] / s[:3] / s[2:]Slicing: start:stop (stop exclusive)
s[::-1]Reverse string
s.upper() / s.lower()Change case
s.strip() / s.lstrip() / s.rstrip()Strip whitespace from both / left / right
s.split(",") / s.split()Split on delimiter / split on any whitespace
",".join(["a", "b", "c"])Join list into string: "a,b,c"
s.replace("old", "new")Replace all occurrences
s.find("sub") / s.index("sub")First index of substring - find returns -1, index raises ValueError
s.startswith("pre") / s.endswith("suf")Check prefix / suffix
"sub" in sTrue if substring found
s.count("x")Count non-overlapping occurrences
s.zfill(5)Left-pad with zeros to width: "0042"
s.center(20, "-")Centre string in field of width padded with char
"""multiline\nstring"""Triple-quoted string - preserves newlines
r"\n is literal"Raw string - backslashes not treated as escapes

Lists, Tuples & Sets

lst = [1, 2, 3]List literal - mutable, ordered
lst.append(4)Add to end
lst.extend([4, 5])Add all items from iterable
lst.insert(1, "x")Insert at index
lst.pop() / lst.pop(0)Remove and return last / item at index
lst.remove("x")Remove first occurrence of value (raises ValueError if missing)
del lst[1]Delete item at index
lst[1:3] = []Delete a slice
len(lst)Number of items
"x" in lstTrue if value exists
lst.index("x")First index of value
lst.count("x")Number of occurrences
lst.sort() / lst.sort(reverse=True)Sort in place
sorted(lst) / sorted(lst, key=len)Return new sorted list
lst.reverse()Reverse in place
lst + [4, 5]Concatenate - returns new list
lst * 3Repeat list N times
list(range(5))Create list from range: [0,1,2,3,4]
tup = (1, 2, 3)Tuple - immutable; single-item tuple needs trailing comma: (1,)
a, b = tup[:2]Unpack tuple
s = {1, 2, 3}Set - unordered, unique elements
s.add(4) / s.discard(2)Add element / remove if present (no error)
s1 | s2 / s1 & s2 / s1 - s2 / s1 ^ s2Union / intersection / difference / symmetric difference
s1.issubset(s2) / s1.issuperset(s2)Subset / superset check

Dicts

d = {"a": 1, "b": 2}Dict literal
d["a"]Access by key - raises KeyError if missing
d.get("a") / d.get("a", 0)Safe access - returns None or default if missing
d["c"] = 3Add or update key
del d["a"]Remove key (raises KeyError if missing)
d.pop("a") / d.pop("a", None)Remove and return value / with default
"a" in dTrue if key exists
d.keys() / d.values() / d.items()View objects of keys / values / (key, value) pairs
d.update({"c": 3})Merge another dict (in place)
{**d1, **d2}Merge dicts - d2 values win on duplicate keys
d | {"c": 3}Merge with | operator (Python 3.9+)
d.setdefault("a", 0)Return value if key exists, else insert and return default
dict.fromkeys(["a","b"], 0)Create dict with keys from iterable, all set to default
len(d)Number of key-value pairs
for k, v in d.items():Iterate key-value pairs

Control Flow

if x > 0:Indentation defines blocks - no braces
if x > 0: ... elif x < 0: ... else: ...if / elif / else
"pos" if x > 0 else "neg"Ternary / conditional expression
for item in iterable:Iterate over any iterable
for i, val in enumerate(lst):Iterate with index
for a, b in zip(lst1, lst2):Iterate two lists in parallel
for k, v in d.items():Iterate dict key-value pairs
for i in range(10): / range(2, 10) / range(0, 10, 2)Range: stop / start,stop / start,stop,step
while condition:Loop while condition is true
break / continue / passExit loop / skip iteration / no-op placeholder
for ... else: / while ... else:else block runs if loop completed without break
match x:Structural pattern matching (Python 3.10+)
case 1: / case str(): / case [a, b]: / case _:Literal / type / sequence / wildcard pattern

Functions

def greet(name): return f"Hello, {name}"Function definition
def greet(name: str) -> str:With type hints
def greet(name="World"):Default parameter value
def fn(*args):Variadic positional args - collected as tuple
def fn(**kwargs):Variadic keyword args - collected as dict
def fn(*args, **kwargs):Accept any combination of positional and keyword args
fn(a, b, *lst)Unpack list as positional args
fn(**{"a": 1})Unpack dict as keyword args
lambda x: x * 2Anonymous function - single expression
lambda x, y: x + yLambda with multiple params
global xDeclare intent to modify a global variable
nonlocal xDeclare intent to modify a variable in enclosing scope
def outer():\n def inner(): ...\n return innerClosure - inner function captures outer scope
from functools import lru_cache\n@lru_cacheMemoisation decorator

Classes

class Dog:Class definition
class Dog(Animal):Inherit from Animal
def __init__(self, name):\n self.name = nameConstructor - self is the instance
def bark(self): ...Instance method - first param is always self
@classmethod\ndef create(cls): ...Class method - receives the class, not instance
@staticmethod\ndef helper(): ...Static method - no implicit first argument
@property\ndef name(self): return self._nameGetter property
@name.setter\ndef name(self, val): self._name = valSetter property
super().__init__(args)Call parent class constructor
isinstance(obj, Dog)True if obj is a Dog (or subclass)
issubclass(Dog, Animal)True if Dog inherits from Animal
def __str__(self): return self.name__str__ - called by str() and print()
def __repr__(self): return f"Dog({self.name!r})"__repr__ - unambiguous representation for debugging
def __len__(self): / __eq__(self, other): / __lt__(self, other):Dunder methods for len(), ==, <
from dataclasses import dataclass\n@dataclass\nclass Point:\n x: float\n y: floatDataclass - auto-generates __init__, __repr__, __eq__

Comprehensions & Generators

[x * 2 for x in lst]List comprehension - transform each item
[x for x in lst if x > 0]List comprehension with filter
[f(x) for x in lst if pred(x)]Transform + filter combined
[x for row in matrix for x in row]Nested loops - flattens 2D list
{k: v for k, v in d.items()}Dict comprehension
{k: v for k, v in d.items() if v > 0}Dict comprehension with filter
{x * 2 for x in lst}Set comprehension - deduplicated results
(x * 2 for x in lst)Generator expression - lazy, memory-efficient
sum(x * 2 for x in lst)Pass generator directly to a function
list(map(fn, lst))map() - equivalent to [fn(x) for x in lst]
list(filter(pred, lst))filter() - equivalent to [x for x in lst if pred(x)]
from functools import reduce\nreduce(lambda a, b: a + b, lst)reduce() - fold list to single value

Common Built-ins

print(x, y, sep=", ", end="")Print with custom separator and line ending
input("Prompt: ")Read a line from stdin as string
range(start, stop, step)Lazy integer sequence
len(x) / sum(x) / min(x) / max(x)Length / sum / min / max of iterable
abs(x) / round(x, 2) / pow(x, n)Absolute value / round / exponent
sorted(x, key=fn, reverse=True)Return sorted list
reversed(lst)Return reverse iterator (wrap in list() to materialise)
zip(a, b, strict=True)Pair up iterables; strict=True raises if lengths differ
enumerate(lst, start=1)Pairs of (index, value)
any(pred(x) for x in lst)True if any element is truthy
all(pred(x) for x in lst)True if all elements are truthy
open("file.txt", "r") as fOpen file for reading
f.read() / f.readlines() / f.readline()Read all / lines list / one line
open("file.txt", "w") as f:\n f.write("text")Open for writing (truncates)
import os\nos.path.exists(p) / os.path.join(a, b)File path utilities
import json\njson.dumps(obj) / json.loads(s)Encode to JSON string / decode from JSON string
import re\nre.search(r"pattern", s)Regex search - returns Match or None
from datetime import datetime\ndatetime.now()Current local datetime
from copy import copy, deepcopyShallow copy / deep copy

Error Handling

try:\n ...\nexcept ValueError as e:\n ...Catch specific exception
except (TypeError, ValueError) as e:Catch multiple exception types
except Exception as e:Catch any exception (broad catch)
except:Bare except - catches everything including SystemExit; avoid
else:else block runs only if no exception was raised
finally:finally block always runs - use for cleanup
raise ValueError("bad input")Raise an exception
raise ValueError("msg") from original_errorChain exceptions - preserves original traceback
raise # bare raiseRe-raise the current exception
class AppError(Exception):\n passCustom exception class
class ValidationError(AppError):\n def __init__(self, field, msg):\n super().__init__(f"{field}: {msg}")Custom exception with fields
str(e) / repr(e)Exception message / full representation
import traceback\ntraceback.print_exc()Print full traceback to stderr
traceback.format_exc()Get full traceback as string
with open("file.txt") as f:Context manager - file closed automatically on exit or error
class Managed:\n def __enter__(self): return self\n def __exit__(self, exc_type, exc, tb): ...Implement context manager protocol
from contextlib import contextmanager\n@contextmanager\ndef managed():\n yield valueGenerator-based context manager
from contextlib import suppress\nwith suppress(FileNotFoundError):\n os.remove(path)Silently ignore specific exceptions

Modules & Imports

import osImport module - access as os.path.join()
import os as operating_systemImport with alias
from os import path, getcwdImport specific names
from os.path import join, existsImport from sub-module
from . import moduleRelative import from same package
from ..utils import helperRelative import from parent package
if __name__ == '__main__': main()Only run as script, not when imported
__all__ = ["MyClass", "my_func"]Control what from module import * exports
import importlib\nimportlib.reload(module)Reload a module at runtime
pip install requestsInstall a package
pip install -r requirements.txtInstall from requirements file
pip freeze > requirements.txtSave current environment to requirements file
python -m venv .venvCreate virtual environment
source .venv/bin/activateActivate virtual environment (Linux/macOS)
.venv\Scripts\activateActivate virtual environment (Windows)
python -m module_nameRun module as script

Standard Library Highlights

from pathlib import Path\nPath("dir/file.txt").read_text()Read file with pathlib
Path("dir/file.txt").write_text("content")Write file
Path("dir").mkdir(parents=True, exist_ok=True)Create directory tree
list(Path(".").glob("**/*.py"))Recursive glob
import shutil\nshutil.copy(src, dst) / shutil.move(src, dst)Copy / move files
shutil.rmtree("dir")Remove directory tree recursively
from collections import defaultdict\ndd = defaultdict(list)Dict with automatic default value
from collections import Counter\nCounter(["a","b","a"])Count element frequencies: Counter({"a":2,"b":1})
from collections import deque\ndq = deque(maxlen=100)Double-ended queue with optional max length
from itertools import chain, product, combinations, permutationsCommon itertools
list(chain([1,2],[3,4]))Flatten iterables: [1,2,3,4]
list(combinations("ABC", 2))All combinations of length 2
import sys\nsys.argv / sys.exit(1) / sys.pathCLI args / exit / module search paths
import subprocess\nresult = subprocess.run(["ls", "-la"], capture_output=True, text=True)Run subprocess and capture output
import threading\nt = threading.Thread(target=fn, args=(x,))\nt.start(); t.join()Run function in thread
import logging\nlogging.basicConfig(level=logging.INFO)\nlogging.info("msg")Basic logging setup