A complete Python cheatsheet — every major concept in one page: syntax, strings,
lists/dicts, OOP, exceptions, generators, decorators, concurrency, files, pip/venv, coding
templates, and interview traps. Ideal for last-minute revision.
Quick Reference
Python Programming Cheatsheet
Every major Python concept on one page — program structure, types, operators, control flow,
strings, lists and dicts, functions, OOP, dunders, exceptions, modules, files, comprehensions,
stdlib highlights, typing, asyncio, testing, coding templates, version notes, and interview
traps. Built for revision before interviews and for looking things up while you code.
print("Hello, Python!")
defmain() -> None:
name = "Ravi"print(f"Hello, {name}!")
if __name__ == "__main__":
main()
Run, modules, venv
python hello.py # run a script
python -m pip install requests
python -m venv .venv # create virtual env# Windows: .venv\Scripts\activate# Unix: source .venv/bin/activate
python -c "print(2+2)" # one-liner
python -i script.py # run then drop into REPL
python -m http.server 8000
print / input
print("a", "b", sep="-", end="!\n")
print(f"{42:05d} | {3.14159:.2f}")
name = input("Name: ")
age = int(input("Age: "))
# Multiple values from one line
a, b = map(int, input().split())
Command-line arguments
import sys
# python greeter.py Ravi 21iflen(sys.argv) < 3:
sys.exit("usage: greeter.py NAME AGE")
name, age = sys.argv[1], int(sys.argv[2])
print(f"{name} is {age}")
Rules: Indentation defines blocks (usually 4 spaces). No semicolons needed. # starts a comment. The entry guard if __name__ == "__main__": keeps importable modules from running side effects.
🗄️
Data Types, Variables & Casting
Built-in scalar types
Type
Examples
Truthy?
Notes
int
42, 1_000, 0x2A, 0b1010
nonzero
Arbitrary precision
float
3.14, 1e-3, float("inf")
nonzero
IEEE-754 double
complex
3+4j
nonzero
.real, .imag
bool
True, False
True only
Subclass of int
str
"hi", 'hi', """..."""
nonempty
Immutable Unicode
bytes
b"hi", bytes(3)
nonempty
Immutable 0–255
NoneType
None
never
Singleton null
Collections at a glance
Type
Mutable
Ordered*
Typical use
list
yes
yes
Sequence of items
tuple
no
yes
Fixed record / hashable
dict
yes
yes (3.7+)
Key → value map
set
yes
no
Unique membership
frozenset
no
no
Hashable set
Literals & casting
n = 42
x = 3.14
s = "42"
b = True
nothing = Noneint("42"); float("3.14"); str(42)
bool(0) # Falsebool([]) # Falselist("abc") # ['a', 'b', 'c']tuple([1, 2])
set([1, 1, 2]) # {1, 2}dict(a=1, b=2)
Identity, equality, truthiness
a = [1]; b = [1]
a == b # True (value)
a is b # False (identity)
a isnotNone# preferred null check# Falsy: None, False, 0, 0.0, "", [], {}, set()if items: # nonempty?process(items)
Multiple assignment & unpacking
x, y = 1, 2
x, y = y, x # swap
a, *mid, z = [1, 2, 3, 4] # mid = [2, 3]
first, second = "ab"
match command.split():
case ["quit"]:
returncase ["load", filename]:
load(filename)
case ["move", x, y] ifint(x) >= 0:
move(int(x), int(y))
case _:
print("unknown")
for / while / else
for i inrange(5):
if i == 3:
breakif i % 2 == 0:
continueprint(i)
else:
print("no break") # runs if loop finished
n = 3while n > 0:
n -= 1
range & enumerate
range(5) # 0..4range(2, 10, 2) # 2,4,6,8range(5, 0, -1) # 5..1for i, item inenumerate(items, start=1):
print(i, item)
for a, b inzip(xs, ys):
print(a, b)
match patterns (3.10+)
Pattern
Matches
case 1:
Equality to 1
case "go":
String literal
case [x, y]:
Sequence of length 2
case {"k": v}:
Mapping with key k
case Point(x=0, y=y):
Class __match_args__ / keywords
case _:
Wildcard (default)
case x if x > 0:
Capture + guard
Loop helpers
Pattern
Code
Use
Index + value
enumerate(seq)
Need position
Parallel iter
zip(a, b)
Pair sequences
Sorted keys
for k in sorted(d)
Stable key order
Reverse
reversed(seq)
View, not copy
Early exit
break / return
Stop searching
Skip
continue
Next iteration
No-op body
pass
Placeholder
Loop else: runs only when the loop did notbreak. Handy for search-not-found patterns.
🔤
Strings & Text
Create & escape
s = "hello"
t = 'world'
m = """multi
line"""
raw = r"C:\new\path"# backslashes keptf"x={1+1}"# f-stringb"bytes"# bytes literal
Prefer f-strings for readability. Use !r when debugging (f"{obj!r}"). For user-facing templates with untrusted input, avoid str.format on attacker-controlled format strings.
📑
Lists, Tuples & Sequences
List essentials
xs = [1, 2, 3]
xs.append(4)
xs.extend([5, 6])
xs.insert(0, 0)
xs.pop() # last
xs.pop(0) # by index
xs.remove(2) # by value (first)
xs.clear()
ys = xs.copy() # shallow
List algorithms
xs = [3, 1, 2]
xs.sort() # in placesorted(xs, reverse=True) # new list
xs.sort(key=str.lower)
xs.reverse()
xs.count(1); xs.index(2)
# Slice assignment
xs[1:3] = [9, 9]
Tuple & packing
t = (1, 2, 3)
one = (1,) # trailing comma!
a, b, c = t
# Named fields (3.7+ dataclasses preferred for records)from collections import namedtuple
Point = namedtuple("Point", "x y")
p = Point(3, 4)
d = {"a": 1, "b": 2}
d["c"] = 3
d.get("z", 0) # default
d.setdefault("x", []) # get or insertdel d["a"]
d.pop("b", None)
d.keys(); d.values(); d.items()
"a"in d # keys only
Merge & unpack
a = {"x": 1}; b = {"y": 2}
{**a, **b} # merge (right wins)
a | b # 3.9+ union
a |= b # in-placedict.fromkeys(["a", "b"], 0)
# Comprehension
{k: v * 2for k, v in b.items()}
set basics
s = {1, 2, 3}
s.add(4); s.discard(9) # no error
s.remove(1) # KeyError if missing
s | t; s & t; s - t; s ^ t
s <= t # subsetfrozenset(s) # immutable / hashable
try:
n = int(text)
exceptValueErroras e:
print("bad int", e)
except (TypeError, OSError):
raiseelse:
print("ok", n) # no exceptionfinally:
print("always")
raise & custom
classOutOfRange(ValueError):
passdefset_age(age: int) -> None:
if age < 0:
raiseOutOfRange(f"age={age}")
if age > 150:
raiseValueError("too old") fromNone
with / ExitStack
withopen("a.txt") as f:
data = f.read()
from contextlib import suppress, ExitStackwithsuppress(FileNotFoundError):
open("missing.txt").close()
withExitStack() as stack:
files = [stack.enter_context(open(p)) for p in paths]
EAFP vs LBYL
# EAFP — preferred Pythonic styletry:
value = mapping[key]
exceptKeyError:
value = default
# LBYLif key in mapping:
value = mapping[key]
else:
value = default
Built-in exception tree (selected)
Exception
Typical cause
SyntaxError
Invalid source
NameError
Undefined name
TypeError
Wrong type / arity
ValueError
Right type, bad value
IndexError
Sequence index OOB
KeyError
Missing mapping key
AttributeError
Missing attribute
ZeroDivisionError
/ // % by zero
FileNotFoundError
Missing path
StopIteration
Iterator exhausted
RuntimeError
Generic runtime failure
AssertionError
assert failed
Catch specific exceptions. Bare except: or except Exception: too early hides bugs. Use raise ... from e to chain causes.
📦
Modules, Packages & Imports
Import forms
import math
import math as m
from math import sqrt, pi
from math import * # avoid in libsfrom package.sub import util
# Relatives inside a packagefrom . import sibling
from ..core import helper
Package layout
mypkg/
__init__.py # makes a package
util.py
sub/
__init__.py
helpers.py
# Namespace packages (3.3+) may omit __init__.py# pyproject.toml / setup.cfg for installable projects
__name__ & sys.path
import sys
print(__name__) # "__main__" or module name
sys.path.insert(0, "lib")
# Reload during REPL experimentsimport importlib, math
importlib.reload(math)
Resource access
from importlib import resources
# Python 3.9+
text = resources.files("mypkg").joinpath("data.txt").read_text(encoding="utf-8")
Import rules
Rule
Why
Prefer absolute imports
Clearer, refactor-friendly
Avoid from x import *
Pollutes namespace, hides origins
One package idea per dir
Keeps APIs focused
Side-effect-light imports
Importing should be cheap/safe
Use if __name__ == "__main__"
Scripts stay importable
📄
Files, pathlib & JSON
open patterns
withopen("data.txt", "r", encoding="utf-8") as f:
text = f.read()
# f.readline(); f.readlines()withopen("out.txt", "w", encoding="utf-8") as f:
f.write("hello\n")
withopen("log.txt", "a", encoding="utf-8") as f:
f.write("line\n")
# Binarywithopen("img.bin", "rb") as f:
blob = f.read()
pathlib
from pathlib importPath
p = Path("data") / "file.txt"
p.exists(); p.is_file(); p.suffix
p.read_text(encoding="utf-8")
p.write_text("hi", encoding="utf-8")
Path.cwd(); Path.home()
for child inPath(".").glob("**/*.py"):
print(child)
JSON / CSV
import json, csv
json.dumps({"a": 1})
json.loads('{"a": 1}')
withopen("d.json", "w", encoding="utf-8") as f:
json.dump(obj, f, indent=2)
withopen("t.csv", newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
print(row["name"])
temp & shutil
import tempfile, shutil
from pathlib importPathwith tempfile.TemporaryDirectory() as d:
Path(d, "x.txt").write_text("ok", encoding="utf-8")
shutil.copy("a.txt", "b.txt")
shutil.move("b.txt", "c.txt")
shutil.rmtree("old_dir", ignore_errors=True)
pathlib highlights
API
Purpose
Path("a") / "b"
Join parts
.name / .stem / .suffix
Filename pieces
.resolve()
Absolute + normalize
.exists() / .is_dir()
Filesystem checks
.glob("**/*.py")
Pattern walk
.read_text() / .write_text()
Quick text I/O
.mkdir(parents=True, exist_ok=True)
Create dirs
open modes
Mode
Meaning
r
Read text (default)
w
Write text (truncate)
x
Create new, fail if exists
a
Append
b
Binary (combine: rb)
+
Update (r+, w+)
t
Text (default)
Always set encoding="utf-8" for text on Windows. Prefer pathlib.Path over string concatenation for paths.
🔁
Comprehensions, Generators & Iterators
List / set / dict comps
squares = [x * x for x inrange(10) if x % 2 == 0]
unique = {c.lower() for c in"AbBa"}
index = {c: i for i, c inenumerate("abc")}
# Nested
pairs = [(i, j) for i inrange(3) for j inrange(2)]
Generator expressions & yield
gen = (x * x for x inrange(1_000_000))
sum(gen)
defcountdown(n):
while n > 0:
yield n
n -= 1for x incountdown(3):
print(x)
yield from & send
defflatten(nested):
for xs in nested:
yieldfrom xs
defecho():
whileTrue:
x = yieldprint("got", x)
g = echo(); next(g); g.send(10)
Iterator protocol
it = iter([10, 20, 30])
next(it) # 10next(it, None) # default if exhaustedclassCount:
def__init__(self, n): self.n, self.i = n, 0def__iter__(self): return self
def__next__(self):
if self.i >= self.n: raiseStopIteration
self.i += 1return self.i
When to use which
Form
Creates
Use when
[...]
list
Need random access / reuse
{...} set
set
Uniqueness
{k: v}
dict
Mapping build
(...)
generator
Lazy / large / one-pass
yield
generator fn
Stateful streaming
Generators are single-pass. Exhausted generators yield nothing further. Materialize with list(gen) if you need reuse.
📚
Key Standard Library
itertools / functools
import itertools as it
import functools as ft
list(it.islice(it.count(10), 3)) # 10,11,12list(it.chain([1], [2, 3]))
list(it.combinations("ABC", 2))
ft.reduce(lambda a, b: a + b, [1, 2, 3], 0)
@ft.lru_cache(maxsize=128)
deffib(n):
return n if n < 2elsefib(n - 1) + fib(n - 2)
datetime / math / random
from datetime import datetime, timedelta, timezone
now = datetime.now(timezone.utc)
now + timedelta(days=1)
import math, random, statistics
math.sqrt(2); math.gcd(12, 18)
random.choice([1, 2, 3]); random.random()
statistics.mean([1, 2, 3])
re / pathlib extras
import re
re.findall(r"\d+", "a12 b3")
re.sub(r"\s+", " ", "a b")
m = re.match(r"(?P<y>\d{4})-(?P<m>\d{2})", "2026-10")
m.group("y") if m elseNone
from typing importCallable, Iterable, TypeVar, Protocol, Literal, TypedDictT = TypeVar("T")
deffirst(xs: Iterable[T]) -> T | None:
for x in xs:
return x
returnNoneHandler = Callable[[str], int]
classUser(TypedDict):
id: int
name: str
Hints are not enforced at runtime by default. Use mypy, pyright, or ty for checking. from __future__ import annotations postpones evaluation (often helpful).
⚡
Asyncio Essentials
async / await
import asyncio
asyncdeffetch(n: int) -> int:
await asyncio.sleep(0.01)
return n * 2asyncdefmain():
a, b = await asyncio.gather(fetch(1), fetch(2))
print(a, b)
asyncio.run(main())
defclamp(n, lo, hi):
"""
>>> clamp(5, 0, 10)
5
>>> clamp(-1, 0, 10)
0
"""assert lo <= hi
returnmax(lo, min(hi, n))
if __name__ == "__main__":
import doctest
doctest.testmod()
Assertions cheat sheet
unittest
pytest
assertEqual(a, b)
assert a == b
assertTrue(x)
assert x
assertIn(a, b)
assert a in b
assertRaises(E)
pytest.raises(E)
assertAlmostEqual
assert a == pytest.approx(b)
🧰
Coding Templates
CLI script skeleton
#!/usr/bin/env python3from __future__ import annotations
import argparse
from pathlib importPathdefparse_args() -> argparse.Namespace:
p = argparse.ArgumentParser()
p.add_argument("path", type=Path)
return p.parse_args()
defmain() -> None:
args = parse_args()
text = args.path.read_text(encoding="utf-8")
print(len(text))
if __name__ == "__main__":
main()
Freq map / Counter
from collections importCounter
freq = Counter(word.lower() for word in text.split())
print(freq.most_common(5))
Two-pointer / sliding window
defmax_sum_window(xs: list[int], k: int) -> int:
window = sum(xs[:k])
best = window
for i inrange(k, len(xs)):
window += xs[i] - xs[i - k]
best = max(best, window)
return best
BFS / DFS graphs
from collections import deque
defbfs(graph, start):
seen = {start}
q = deque([start])
while q:
u = q.popleft()
for v in graph[u]:
if v notin seen:
seen.add(v)
q.append(v)
return seen
defdfs(graph, start, seen=None):
seen = seen orset()
seen.add(start)
for v in graph[start]:
if v notin seen:
dfs(graph, v, seen)
return seen
Binary search
import bisect
xs = [1, 3, 5, 7]
bisect.bisect_left(xs, 5) # 2
bisect.bisect_right(xs, 5) # 3deflower_bound(a, target):
lo, hi = 0, len(a)
while lo < hi:
mid = (lo + hi) // 2if a[mid] < target:
lo = mid + 1else:
hi = mid
return lo
Safe dict grouping
from collections import defaultdict
groups: dict[str, list[int]] = defaultdict(list)
for name, score in rows:
groups[name].append(score)
Interview building blocks
Problem shape
Tool
Frequency / anagrams
Counter
Top-K
heapq.nlargest / Counter.most_common
Graph short path (unweighted)
BFS + deque
Intervals
sort by start, merge
Prefix sums
running total array
Monotonic stack
next greater element
Memoized recursion
functools.lru_cache / cache
📌
Version Highlights
Modern language features
Version
Highlights
3.8
Walrus :=, f"{x=}", positional-only /
3.9
list[int] builtins, dict |, str.removeprefix
3.10
match/case, X | Y unions, better errors
3.11
Exception groups, tomllib, faster CPython, Self
3.12
Type alias type, f-string formalization, more perf
funcs = [lambda: i for i inrange(3)]
print([f() for f in funcs]) # [2, 2, 2]
funcs = [lambda i=i: i for i inrange(3)]
print([f() for f in funcs]) # [0, 1, 2]
How to use this page: skim the jump chips, drill the tables, then type every snippet once in a REPL or IDE. Pair it with Interview Q&A for spoken answers and Real-life Examples for intuition.