elefcode
← All cheat sheets

Languages

Python Cheat Sheet — Syntax and Built-ins Reference

The Python 3 syntax and built-ins you reach for every day, from slicing and f-strings to comprehensions, classes, and context managers.

Put it into practice with the matching tool.

Run Python in the browser →

Advertisement

Strings

f"Hi {name}, {n:.2f}"f-string with an embedded expression and format spec
s[1:4] s[::-1]Slice characters 1–3 / reverse a string
s.split(",")Split into a list on a separator
", ".join(items)Join a list of strings with a separator
s.strip()Remove leading and trailing whitespace
s.replace("a", "b")Replace every occurrence
s.startswith("x")Prefix test (endswith for suffixes)
s.lower() / s.upper()Change case

Lists, tuples, and sets

xs.append(x)Add one item to the end
xs.extend(ys)Add every item from another iterable
xs.pop()Remove and return the last item
sorted(xs, key=len, reverse=True)Return a new sorted list
len(xs)Number of items
a, b = b, aSwap two variables with tuple unpacking
first, *rest = xsUnpack the head and the remaining items
set(xs)Unique items; use | & - for union, intersection, difference

Dictionaries

d.get("k", default)Read a key without raising KeyError
d.items()Iterate over (key, value) pairs
d.setdefault("k", [])Insert a default if missing and return the value
{**a, **b} / a | bMerge dicts (later keys win)
"k" in dTest whether a key exists
del d["k"]Remove a key

Comprehensions

[x * 2 for x in xs]List comprehension
[x for x in xs if x > 0]Filter while building the list
{k: v for k, v in pairs}Dict comprehension
{x % 3 for x in xs}Set comprehension
sum(x * x for x in xs)Generator expression — lazy, no list built

Control flow

for i, x in enumerate(xs):Loop with an index
for a, b in zip(xs, ys):Loop over two iterables in step
for i in range(0, 10, 2):Loop over 0, 2, 4, 6, 8
x if cond else yConditional expression
match cmd: case "go": ...Structural pattern matching (3.10+)
while (line := f.readline()):Walrus operator: assign inside an expression

Functions and classes

def f(a, b=2, *args, **kwargs):Defaults, extra positional and keyword arguments
lambda x: x + 1Anonymous one-expression function
def f(x: int) -> str:Type hints (not enforced at runtime)
class Dog(Animal):Define a class that inherits from Animal
def __init__(self, name):Constructor
@dataclassAuto-generate __init__, __repr__, and __eq__
@propertyExpose a method as a read-only attribute

Files and errors

with open("f.txt", encoding="utf-8") as f:Open a file and close it automatically
f.read() / f.readlines()Read the whole file / a list of lines
open("f.txt", "w").write(s)Write text (mode "a" appends)
try: ... except ValueError as e: ...Catch a specific exception
finally:Runs whether or not an exception occurred
raise ValueError("bad input")Raise an exception
import json; json.loads(s)Parse JSON (json.dumps to serialise)

Related guides

More cheat sheets