All Cheat Sheets
Python Cheat Sheet
Python cheat sheet covering syntax, f-strings, lists, dicts, comprehensions, functions, classes, dataclasses, exceptions, file handling, venv and pip, generators, and standard library essentials.
Data Types & Variables
Basic types
n = 42 # int
x = 3.14 # float
ok = True # bool
name = "Ada" # str
nothing = NoneCheck type
type(x) # <class 'float'>
isinstance(x, (int, float))Convert
int("7"), float("2.5"), str(10), bool(0), list("abc")Multiple assignment
a, b = 1, 2
a, b = b, a # swapUnpack with rest
first, *rest = [1, 2, 3, 4]Integer math
7 // 2 # 3 (floor div)
7 % 2 # 1
2 ** 10 # 1024Truthiness
if not items: # empty list, "", 0, None are falsy
...Prefer `is None` over `== None`Strings & f-strings
f-string
f"{name} is {age} years old"Format numbers
f"{price:.2f}" # 2 decimals
f"{n:,}" # 1,234,567
f"{ratio:.1%}" # 45.3%Debug f-string
f"{x=}" # 'x=42'Python 3.8+Slicing
s[0], s[-1], s[1:4], s[::-1] # last is reversedSplit & join
"a,b,c".split(",")
", ".join(["a", "b"])Common methods
s.strip(), s.lower(), s.upper(), s.replace("a", "b")
s.startswith("http"), s.find("x"), s.count("a")Multiline / raw
text = """line 1
line 2"""
path = r"C:\new\folder"Raw strings ignore backslash escapesLists, Tuples, Dicts & Sets
List ops
nums = [3, 1, 2]
nums.append(4); nums.extend([5, 6])
nums.insert(0, 9); nums.pop(); nums.remove(9)Sort
nums.sort() # in place
sorted(nums, reverse=True) # new list
sorted(users, key=lambda u: u["age"])Tuple
point = (3, 4)
x, y = point
single = (1,)Immutable; trailing comma makes a 1-tupleDict basics
user = {"name": "Ada", "age": 36}
user["email"] = "[email protected]"
user.get("phone", "n/a")Iterate dict
for key, value in user.items():
print(key, value)Merge dicts
merged = a | b # 3.9+
merged = {**a, **b}Set ops
a = {1, 2, 3}; b = {2, 3, 4}
a | b, a & b, a - b, a ^ bUnion, intersection, difference, symmetric differenceMembership
3 in nums
"name" in user # checks keysO(1) for sets/dicts, O(n) for listsComprehensions
List comprehension
squares = [x * x for x in range(10)]With filter
evens = [x for x in nums if x % 2 == 0]Conditional value
labels = ["even" if x % 2 == 0 else "odd" for x in nums]Dict comprehension
lengths = {w: len(w) for w in words}Set comprehension
unique_domains = {e.split("@")[1] for e in emails}Generator expression
total = sum(x * x for x in range(1_000_000))Lazy — no intermediate list in memoryNested / flatten
flat = [x for row in matrix for x in row]Control Flow
if / elif / else
if score >= 90:
grade = "A"
elif score >= 75:
grade = "B"
else:
grade = "C"Ternary
status = "adult" if age >= 18 else "minor"for with index
for i, item in enumerate(items, start=1):
print(i, item)Loop two lists
for name, score in zip(names, scores):
print(name, score)while / break / continue
while True:
line = input()
if not line:
breakfor ... else
for n in nums:
if n < 0:
break
else:
print("no negatives")else runs only if the loop did not breakmatch (3.10+)
match command.split():
case ["go", direction]:
move(direction)
case ["quit"]:
exit()
case _:
print("unknown")Walrus operator
if (n := len(items)) > 10:
print(f"{n} items")Python 3.8+Functions
Define with defaults
def greet(name: str, greeting: str = "Hello") -> str:
return f"{greeting}, {name}"*args and **kwargs
def log(*args, **kwargs):
print(args) # tuple of positional args
print(kwargs) # dict of keyword argsKeyword-only args
def connect(host, *, timeout=5):
...
connect("db", timeout=10)Unpack into call
args = [1, 2]; opts = {"sep": "-"}
print(*args, **opts)Lambda
square = lambda x: x * x
sorted(pairs, key=lambda p: p[1])Mutable default trap
def add(item, items=None):
if items is None:
items = []
items.append(item)
return itemsNever use [] or {} as a default valueType hints
from typing import Optional
def find(id: int) -> Optional[dict]: ...
def tags() -> list[str]: ...Built-in generics (list[str]) need 3.9+; `X | None` needs 3.10+Decorator
import functools
def timed(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
return fn(*args, **kwargs)
return wrapperClasses & Dataclasses
Class
class Dog:
species = "canine" # class attribute
def __init__(self, name):
self.name = name # instance attribute
def speak(self):
return f"{self.name} says woof"Inheritance
class Puppy(Dog):
def speak(self):
return super().speak() + "!"String representation
def __repr__(self):
return f"Dog(name={self.name!r})"Property
@property
def full_name(self):
return f"{self.first} {self.last}"Class / static method
@classmethod
def from_dict(cls, d): return cls(**d)
@staticmethod
def is_valid(name): return bool(name)Dataclass
from dataclasses import dataclass, field
@dataclass
class User:
name: str
age: int = 0
tags: list[str] = field(default_factory=list)Auto-generates __init__, __repr__, __eq__; add frozen=True for immutabilityExceptions
try / except
try:
value = int(text)
except ValueError as e:
print(f"bad input: {e}")Multiple + else/finally
try:
f = open(path)
except (FileNotFoundError, PermissionError):
...
else:
data = f.read() # runs if no exception
finally:
cleanup() # always runsRaise
raise ValueError("age must be positive")Custom exception
class NotFoundError(Exception):
passChain exceptions
except KeyError as e:
raise ConfigError("missing key") from eFiles, pathlib & JSON
Read file
with open("data.txt", encoding="utf-8") as f:
text = f.read()Read lines
with open("data.txt") as f:
for line in f:
print(line.rstrip())Write / append
with open("out.txt", "w") as f: # "a" to append
f.write("hello\n")pathlib
from pathlib import Path
p = Path("src") / "app.py"
p.exists(), p.suffix, p.stem, p.parent
text = p.read_text()
p.write_text("print(1)")Glob files
for f in Path(".").rglob("*.py"):
print(f)JSON
import json
data = json.loads(text)
text = json.dumps(data, indent=2)
with open("d.json") as f:
data = json.load(f)CSV
import csv
with open("users.csv", newline="") as f:
for row in csv.DictReader(f):
print(row["email"])Modules, venv & pip
Import
import os
from collections import Counter
import numpy as npRun as script
if __name__ == "__main__":
main()Create venv
python3 -m venv .venvActivate venv
source .venv/bin/activate # macOS/Linux
.venv\Scripts\activate # WindowsInstall packages
pip install requests
pip install -r requirements.txtFreeze deps
pip freeze > requirements.txtRun a module
python -m http.server 8000Iterators & Generators
Generator function
def countdown(n):
while n > 0:
yield n
n -= 1
for i in countdown(3): print(i)Manual iteration
it = iter([1, 2, 3])
next(it) # 1
next(it, None) # default instead of StopIterationyield from
def chain(*iterables):
for it in iterables:
yield from itInfinite range
import itertools
for i in itertools.count(1): ...Context manager
from contextlib import contextmanager
@contextmanager
def timer():
start = time.perf_counter()
yield
print(time.perf_counter() - start)Standard Library & Interview Idioms
Counter
from collections import Counter
Counter("banana").most_common(2) # [('a', 3), ('n', 2)]defaultdict
from collections import defaultdict
groups = defaultdict(list)
groups[key].append(item)deque
from collections import deque
q = deque([1, 2]); q.appendleft(0); q.popleft()O(1) appends/pops at both ends — use for queues/BFSitertools
from itertools import chain, groupby, combinations, permutations, product
list(combinations([1, 2, 3], 2)) # [(1, 2), (1, 3), (2, 3)]datetime
from datetime import datetime, timedelta, timezone
now = datetime.now(timezone.utc)
tomorrow = now + timedelta(days=1)
now.strftime("%Y-%m-%d %H:%M")
datetime.fromisoformat("2025-01-31T10:00:00")heapq
import heapq
heapq.nsmallest(3, nums)
heapq.heappush(h, x); heapq.heappop(h)Min-heap; push negatives for a max-heapMemoize
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n): return n if n < 2 else fib(n - 1) + fib(n - 2)Two-sum with a dict
seen = {}
for i, n in enumerate(nums):
if target - n in seen:
return [seen[target - n], i]
seen[n] = iReverse & palindrome
s[::-1]
s == s[::-1]Anagram check
sorted(a) == sorted(b)
Counter(a) == Counter(b)Dedupe keeping order
list(dict.fromkeys(items))Min/max by key
max(users, key=lambda u: u["score"])Transpose matrix
list(zip(*matrix))Keep the references coming
One email a week: new and trending developer tools, fresh comparisons, and what shipped. Unsubscribe in one click.

