developer reference

Python cheat sheet

A practical Python reference with search, one-click copy and printable PDF output.

Go to commands
21
commands
8
categories
0
dependencies

21 commands visible

Types

4 commands
list

List: ordered, mutable, allows duplicates

Typessafe
Practical example
l = [1, 2, 3]
l.append(4)       # append to the end
l.insert(0, 0)    # insert at a position
l.extend([5,6])   # extend the list
l.pop()           # remove and return the last item
l.sort(key=lambda x: -x)   # sort
dict

Dictionary: key→value, preserves order (3.7+)

Typessafe
Practical example
d = {"a": 1, "b": 2}
d.get("c", 0)     # value with a fallback
d.items()         # pairs (k, v)
d.update({"c": 3})
d.pop("a")        # remove a key
d = {**d1, **d2}  # merge (3.9+: d1|d2)
set

Set: unique, unordered, set operations

Typessafe
Practical example
s = {1, 2, 3}
s.add(4)
s.discard(99)     # no error if absent
s1 & s2           # intersection
s1 | s2           # union
s1 - s2           # difference
tuple

Immutable tuple; hashable and usable as a dictionary key only when every element is hashable

Typessafe
Practical example
t = (1, 2, 3)
x, y, z = t       # unpacking
a, *rest = t      # star unpacking

Strings

3 commands
f-string

Modern string interpolation (3.6+)

Stringssafe
Practical example
name = "Enzo"
f"Hello {name}"
f"{3.14159:.2f}"   # 2 decimal places → "3.14"
f"{100_000:,}"    # thousands → "100,000"
f"{name!r}"       # repr
str methods

Most common string methods

Stringssafe
Practical example
s = "  Hello World  "
s.strip()         # strip whitespace
s.lower() / s.upper()
s.split(",")      # split on a separator
",".join(["a","b","c"])   # "a,b,c"
s.replace("Hello","Hi")
s.startswith("He") / s.endswith("d")
str slicing

Slicing and indexing

Stringssafe
Practical example
s = "Hello"
s[0]    # "H"
s[-1]   # "o"
s[1:4]  # "ell"
s[::-1] # "olleH" (reverse)
s[::2]  # "Hlo" (step)

Functions

4 commands
def

Function definition with defaults, *args and **kwargs

Functionssafe
Practical example
def greet(name, greeting="Hello"):
    return f"{greeting}, {name}"

def multi(*args, **kwargs):
    print(args)    # tuple
    print(kwargs)  # dictionary
lambda

Inline anonymous function

Functionssafe
Practical example
sq = lambda x: x**2
sorted(data, key=lambda x: x["age"])
filter(lambda x: x>0, nums)
decorator

Function that wraps another function

Functionssafe
Practical example
import functools

def log(func):
    @functools.wraps(func)
    def wrapper(*a, **kw):
        print(f"Calling {func.__name__}")
        return func(*a, **kw)
    return wrapper

@log
def add(a, b): return a+b
yield

Generator: produces lazy values

Functionssafe
Practical example
def countdown(n):
    while n > 0:
        yield n
        n -= 1

for x in countdown(5): print(x)

Comprehensions

3 commands
list comp

List comprehension with optional filter

Comprehensionssafe
Practical example
[x**2 for x in range(10)]
[x for x in data if x > 0]
[(x, y) for x in a for y in b]  # nested
dict comp

Dict comprehension

Comprehensionssafe
Practical example
{k: v for k, v in items.items() if v}
{word: len(word) for word in words}
generator expr

Generator expression: produces values lazily without building the full result list

Comprehensionssafe
Practical example
total = sum(x**2 for x in range(1000))
any(x > 100 for x in values)
next(x for x in data if x["id"]==5)

Classes

2 commands
class

Class definition with __init__, property and classmethod

Classessafe
Practical example
class Circle:
    def __init__(self, r): self.r = r

    @property
    def area(self): return 3.14 * self.r**2

    @classmethod
    def unit(cls): return cls(1)

    def __repr__(self): return f"Circle(r={self.r})"
dataclass

Class with automatic boilerplate (3.7+)

Classessafe
Practical example
from dataclasses import dataclass, field

@dataclass
class Point:
    x: float
    y: float
    label: str = ""
    tags: list = field(default_factory=list)

p = Point(1.0, 2.0)

File I/O

2 commands
open / pathlib

Reading and writing files

File I/Osafe
Practical example
# read
with open("f.txt") as f:
    data = f.read()

# write
with open("f.txt","w") as f:
    f.write("hello")

# pathlib (recommended)
from pathlib import Path
p = Path("data/file.txt")
p.read_text() / p.write_text("x")
list(Path(".").glob("**/*.py"))
json

JSON serialization

File I/Osafe
Practical example
import json

data = {"key": [1, 2, 3]}
json.dumps(data, indent=2)
json.loads('{"a":1}')

with open("f.json","w") as f:
    json.dump(data, f, indent=2)

Exceptions

1 commands
try / except

Exception handling with finally and raise

Exceptionssafe
Practical example
try:
    result = 1 / x
except ZeroDivisionError as e:
    print(f"Errore: {e}")
except (TypeError, ValueError):
    raise
finally:
    cleanup()

# raise a custom error
raise ValueError(f"Invalid value: {x}")

Built-in

2 commands
map / filter / zip

Higher-order functions on containers

Built-insafe
Practical example
list(map(str, [1,2,3]))       # ["1","2","3"]
list(filter(None, [0,1,2]))   # [1,2]
list(zip([1,2],[3,4]))        # [(1,3),(2,4)]
enumerate / sorted / any / all

Essential built-in utilities

Built-insafe
Practical example
for i, v in enumerate(items, 1): ...
sorted(data, key=lambda x: x["n"], reverse=True)
any(x > 10 for x in vals)
all(isinstance(x, int) for x in vals)

How to use this Python cheat sheet

Can every tuple be used as a dictionary key?

No. A tuple is hashable only if every contained element is hashable. (1, 2) can be a key, but (1, [2]) cannot.

Can I print this sheet as a PDF?

Use Print PDF. The printable version includes all commands and practical examples, including sections hidden by a search.

Can I use it locally?

Yes. Serve the static files with a local HTTP server. Search, filters and copying run in your browser; the Regex tester requires a worker-enabled HTTP context.