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 typesn = 42 # int x = 3.14 # float ok = True # bool name = "Ada" # str nothing = None
Check typetype(x) # <class 'float'> isinstance(x, (int, float))
Convertint("7"), float("2.5"), str(10), bool(0), list("abc")
Multiple assignmenta, b = 1, 2 a, b = b, a # swap
Unpack with restfirst, *rest = [1, 2, 3, 4]
Integer math7 // 2 # 3 (floor div) 7 % 2 # 1 2 ** 10 # 1024
Truthinessif not items: # empty list, "", 0, None are falsy ...Prefer `is None` over `== None`

Strings & f-strings

f-stringf"{name} is {age} years old"
Format numbersf"{price:.2f}" # 2 decimals f"{n:,}" # 1,234,567 f"{ratio:.1%}" # 45.3%
Debug f-stringf"{x=}" # 'x=42'Python 3.8+
Slicings[0], s[-1], s[1:4], s[::-1] # last is reversed
Split & join"a,b,c".split(",") ", ".join(["a", "b"])
Common methodss.strip(), s.lower(), s.upper(), s.replace("a", "b") s.startswith("http"), s.find("x"), s.count("a")
Multiline / rawtext = """line 1 line 2""" path = r"C:\new\folder"Raw strings ignore backslash escapes

Lists, Tuples, Dicts & Sets

List opsnums = [3, 1, 2] nums.append(4); nums.extend([5, 6]) nums.insert(0, 9); nums.pop(); nums.remove(9)
Sortnums.sort() # in place sorted(nums, reverse=True) # new list sorted(users, key=lambda u: u["age"])
Tuplepoint = (3, 4) x, y = point single = (1,)Immutable; trailing comma makes a 1-tuple
Dict basicsuser = {"name": "Ada", "age": 36} user["email"] = "[email protected]" user.get("phone", "n/a")
Iterate dictfor key, value in user.items(): print(key, value)
Merge dictsmerged = a | b # 3.9+ merged = {**a, **b}
Set opsa = {1, 2, 3}; b = {2, 3, 4} a | b, a & b, a - b, a ^ bUnion, intersection, difference, symmetric difference
Membership3 in nums "name" in user # checks keysO(1) for sets/dicts, O(n) for lists

Comprehensions

List comprehensionsquares = [x * x for x in range(10)]
With filterevens = [x for x in nums if x % 2 == 0]
Conditional valuelabels = ["even" if x % 2 == 0 else "odd" for x in nums]
Dict comprehensionlengths = {w: len(w) for w in words}
Set comprehensionunique_domains = {e.split("@")[1] for e in emails}
Generator expressiontotal = sum(x * x for x in range(1_000_000))Lazy — no intermediate list in memory
Nested / flattenflat = [x for row in matrix for x in row]

Control Flow

if / elif / elseif score >= 90: grade = "A" elif score >= 75: grade = "B" else: grade = "C"
Ternarystatus = "adult" if age >= 18 else "minor"
for with indexfor i, item in enumerate(items, start=1): print(i, item)
Loop two listsfor name, score in zip(names, scores): print(name, score)
while / break / continuewhile True: line = input() if not line: break
for ... elsefor n in nums: if n < 0: break else: print("no negatives")else runs only if the loop did not break
match (3.10+)match command.split(): case ["go", direction]: move(direction) case ["quit"]: exit() case _: print("unknown")
Walrus operatorif (n := len(items)) > 10: print(f"{n} items")Python 3.8+

Functions

Define with defaultsdef greet(name: str, greeting: str = "Hello") -> str: return f"{greeting}, {name}"
*args and **kwargsdef log(*args, **kwargs): print(args) # tuple of positional args print(kwargs) # dict of keyword args
Keyword-only argsdef connect(host, *, timeout=5): ... connect("db", timeout=10)
Unpack into callargs = [1, 2]; opts = {"sep": "-"} print(*args, **opts)
Lambdasquare = lambda x: x * x sorted(pairs, key=lambda p: p[1])
Mutable default trapdef add(item, items=None): if items is None: items = [] items.append(item) return itemsNever use [] or {} as a default value
Type hintsfrom 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+
Decoratorimport functools def timed(fn): @functools.wraps(fn) def wrapper(*args, **kwargs): return fn(*args, **kwargs) return wrapper

Classes & Dataclasses

Classclass Dog: species = "canine" # class attribute def __init__(self, name): self.name = name # instance attribute def speak(self): return f"{self.name} says woof"
Inheritanceclass Puppy(Dog): def speak(self): return super().speak() + "!"
String representationdef __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)
Dataclassfrom 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 immutability

Exceptions

try / excepttry: value = int(text) except ValueError as e: print(f"bad input: {e}")
Multiple + else/finallytry: f = open(path) except (FileNotFoundError, PermissionError): ... else: data = f.read() # runs if no exception finally: cleanup() # always runs
Raiseraise ValueError("age must be positive")
Custom exceptionclass NotFoundError(Exception): pass
Chain exceptionsexcept KeyError as e: raise ConfigError("missing key") from e

Files, pathlib & JSON

Read filewith open("data.txt", encoding="utf-8") as f: text = f.read()
Read lineswith open("data.txt") as f: for line in f: print(line.rstrip())
Write / appendwith open("out.txt", "w") as f: # "a" to append f.write("hello\n")
pathlibfrom 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 filesfor f in Path(".").rglob("*.py"): print(f)
JSONimport json data = json.loads(text) text = json.dumps(data, indent=2) with open("d.json") as f: data = json.load(f)
CSVimport csv with open("users.csv", newline="") as f: for row in csv.DictReader(f): print(row["email"])

Modules, venv & pip

Importimport os from collections import Counter import numpy as np
Run as scriptif __name__ == "__main__": main()
Create venvpython3 -m venv .venv
Activate venvsource .venv/bin/activate # macOS/Linux .venv\Scripts\activate # Windows
Install packagespip install requests pip install -r requirements.txt
Freeze depspip freeze > requirements.txt
Run a modulepython -m http.server 8000

Iterators & Generators

Generator functiondef countdown(n): while n > 0: yield n n -= 1 for i in countdown(3): print(i)
Manual iterationit = iter([1, 2, 3]) next(it) # 1 next(it, None) # default instead of StopIteration
yield fromdef chain(*iterables): for it in iterables: yield from it
Infinite rangeimport itertools for i in itertools.count(1): ...
Context managerfrom contextlib import contextmanager @contextmanager def timer(): start = time.perf_counter() yield print(time.perf_counter() - start)

Standard Library & Interview Idioms

Counterfrom collections import Counter Counter("banana").most_common(2) # [('a', 3), ('n', 2)]
defaultdictfrom collections import defaultdict groups = defaultdict(list) groups[key].append(item)
dequefrom collections import deque q = deque([1, 2]); q.appendleft(0); q.popleft()O(1) appends/pops at both ends — use for queues/BFS
itertoolsfrom itertools import chain, groupby, combinations, permutations, product list(combinations([1, 2, 3], 2)) # [(1, 2), (1, 3), (2, 3)]
datetimefrom 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")
heapqimport heapq heapq.nsmallest(3, nums) heapq.heappush(h, x); heapq.heappop(h)Min-heap; push negatives for a max-heap
Memoizefrom 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 dictseen = {} for i, n in enumerate(nums): if target - n in seen: return [seen[target - n], i] seen[n] = i
Reverse & palindromes[::-1] s == s[::-1]
Anagram checksorted(a) == sorted(b) Counter(a) == Counter(b)
Dedupe keeping orderlist(dict.fromkeys(items))
Min/max by keymax(users, key=lambda u: u["score"])
Transpose matrixlist(zip(*matrix))

Keep the references coming

One email a week: new and trending developer tools, fresh comparisons, and what shipped. Unsubscribe in one click.