All cheatsheets

Cheatsheets

Python

Syntax, comprehensions, the standard library, idioms, OOP, and type hints.

Practice this

Visualize

Python — list slicing [start:stop:step]

stop is exclusive, step can reverse with -1, and negative indices count from the end.

0-6
1-5
2-4
3-3
4-2
5-1
nums[1:4][203040]
positive 0…5 above · negative -6…-1 below each box

start=1 up to stop=4 — stop is excluded.

26 entries

Basics & types7

x = 5 # dynamic typing

Assignment

f"{name} is {age}"

f-string — inline expressions in a string (3.6+).

lst = [1, 2, 3]

List (mutable, ordered)

d = {"a": 1}

Dict (key → value)

s = {1, 2, 3}

Set (unique, unordered)

t = (1, 2)

Tuple (immutable)

lst[1:3] lst[::-1]

Slicing — [start:stop:step]; stop is exclusive.

Control & functions7

for i, v in enumerate(lst):

Loop with index and value at once.

[x*2 for x in lst if x > 0]

List comprehension — build a list in one expression.

{k: v for k, v in d.items()}

Dict comprehension

def f(a, *args, **kwargs):

Variadic args

lambda x: x + 1

Anonymous function

@decorator

Wrap a function to add behavior without changing its body.

if (n := len(lst)) > 10:

Walrus operator — assign inside an expression (3.8+).

Stdlib & idioms7

with open(p) as f:

Context manager — guarantees cleanup (auto-close).

try: ... except E as e: ... finally:

Exception handling

sorted(lst, key=lambda x: x.k)

Sort by key

zip(a, b) map(fn, it) filter(fn, it)

Functional helpers

import json; json.dumps(obj)

JSON serialise

from pathlib import Path

Filesystem paths

from collections import defaultdict, Counter

Group and count without boilerplate.

OOP & typing5

class Foo: def __init__(self, x): self.x = x

Class + constructor

@dataclass class Point: x: int y: int

Dataclass (auto init/repr)

def f(x: int) -> str:

Type hints

list[int] | None

Generic / optional types (3.10+)

__str__ / __repr__ / __eq__

Dunder methods