Cheatsheets
Python
Syntax, comprehensions, the standard library, idioms, OOP, and type hints.
Practice thisVisualize
Python — list slicing [start:stop:step]
stop is exclusive, step can reverse with -1, and negative indices count from the end.
start=1 up to stop=4 — stop is excluded.
26 entries
Basics & types7
x = 5 # dynamic typingAssignment
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 + 1Anonymous function
@decoratorWrap 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 PathFilesystem paths
from collections import defaultdict, CounterGroup and count without boilerplate.
OOP & typing5
class Foo:
def __init__(self, x):
self.x = xClass + constructor
@dataclass
class Point:
x: int
y: intDataclass (auto init/repr)
def f(x: int) -> str:Type hints
list[int] | NoneGeneric / optional types (3.10+)
__str__ / __repr__ / __eq__Dunder methods