Python — Quick Summary
Quick revision: every topic, key terms, and mnemonics for Python.
This is a quick revision doc covering all 41 topics in the Python collection. Open the linked notes if you want depth — this page is for cementing what we already know, fast.
Fundamentals
Variables and Data Types
What it is. Python is dynamically typed — no let/const/var, just assign. The same name can rebind to different types over time.
Key terms.
- Built-in types —
int,float,complex,bool(subclass ofint),str,None. type(x)— exact type.isinstance(x, T)— type or subclass. Preferisinstance.- PEP 8 names —
snake_casevars/functions,PascalCaseclasses,UPPER_SNAKE_CASEconstants, leading_for private-by-convention.
Remember. “A variable is just a label stuck on an object.”
Mutable vs Immutable Types
What it is. Some objects can change in place; others can’t.
Key terms.
- Immutable —
int,float,str,tuple,frozenset,bool,None. Modifying creates a new object (differentid()). - Mutable —
list,dict,set, custom classes. Same object, contents change (sameid()). - Function args — passing a mutable lets the function mutate the original; an immutable can’t be changed externally.
Remember. “Whiteboard vs printed paper. Whiteboard = mutable.”
Strings and String Methods
What it is. Immutable sequences of characters. Methods always return new strings.
Key terms.
- f-string —
f"Hi {name}", supports any expression and format specs ({n:.2f}). - Slicing —
s[start:stop:step].s[::-1]reverses. - Common methods —
strip/lstrip/rstrip,upper/lower/title/capitalize,find/index/count,startswith/endswith,split,join,replace. - Predicates —
isdigit,isalpha,isalnum,isspace.
Remember. “Strings don’t mutate. Capture the return value.”
Lists, Tuples, and Sets
What it is. Three core collection types.
| Type | Ordered | Mutable | Duplicates | Hashable |
|---|---|---|---|---|
list [] | yes | yes | yes | no |
tuple () | yes | no | yes | yes (if all elements hashable) |
set {} | no | yes | no | no |
Key terms.
- List methods —
append,insert,extend,pop,remove,sort,reverse. - Tuple unpacking —
x, y = point;a, *rest = (1,2,3,4); swapa, b = b, a. - Single-element tuple —
(42,)(note the comma). - Set ops —
|union,&intersection,-difference,^symmetric difference.
Remember. “List = notebook. Tuple = receipt. Set = stamps (unique only).”
Dictionaries
What it is. Hash-map of key-value pairs. O(1) average lookup. Insertion-ordered since 3.7.
Key terms.
d[k]vsd.get(k, default)—[]raisesKeyError,getreturns default.keys()/values()/items()— iterators of views.setdefault,update,pop— common mutators.- Merge
|(3.9+) —defaults | overrides. defaultdict(int)fromcollections— auto-create missing keys.
Comprehensions
What it is. One-line builders for lists/dicts/sets and lazy generators.
squares = [n*n for n in range(5)]
evens = [n for n in nums if n % 2 == 0]
labels = ["even" if n % 2 == 0 else "odd" for n in nums]
flat = [x for row in matrix for x in row]
sq_dict = {n: n*n for n in range(5)}
unique = {len(w) for w in words}
total = sum(n*n for n in range(1_000_000)) # generator expression — () not []
Remember. “Brackets build a list. Parens go lazy.”
Type Conversion and Truthiness
What it is. Explicit casts (int(), float(), str(), list(), tuple()). Implicit coercion is rare in Python.
Key terms.
- Falsy —
False,None,0,0.0,"",[],{},set(),(). Everything else is truthy. isvs==—is= same object in memory;=== same value. Useisonly forNone/True/False.- Short-circuit —
orreturns the first truthy (or last);andreturns the first falsy (or last). Both return actual values, not booleans.
Remember. “name = user_input or 'Anonymous'.”
Functions
Functions and Arguments
What it is. def name(params):. Implicit return None if not specified.
Key terms.
- Positional vs keyword args. Defaults must come after non-defaults.
- Mutable default trap —
def f(items=[])shares one list across calls. Fix withitems=Noneand create inside. *argscollects extra positional into a tuple.**kwargscollects keyword args into a dict.- Unpacking on call —
f(*list),f(**dict). - Order rule — positional,
*args, keyword-only,**kwargs.
Remember. Mutable defaults are the #1 Python interview gotcha.
Lambda Functions
What it is. Anonymous one-line function: lambda x: x*2. Single expression only — no statements.
Best use. Inline argument to sorted, map, filter, min/max(..., key=...).
sorted(users, key=lambda u: u["age"])
Remember. “If it doesn’t fit on one line, use def.”
Map, Filter, Reduce, Zip
What it is. Functional helpers that return lazy iterators (map, filter, zip).
Key terms.
map(fn, it)— apply fn to each.filter(fn, it)— keep where fn truthy.filter(None, it)drops falsy items.reduce(fn, it[, init])— fromfunctools. Combines into one value.zip(a, b)— pair element-by-element; stops at shortest. Usezip_longestfromitertoolsto keep all.enumerate(it, start=0)—(index, value)pairs.
Remember. “Map transforms, filter selects, reduce combines, zip pairs.” Comprehensions usually win over map/filter.
Closures and Nonlocal
What it is. Inner functions remember names from enclosing scope, even after the outer returns.
Key terms.
- First-class functions — pass them around, return them, store them.
- Read vs reassign — inner can read outer’s vars, but writing creates a new local. Use
nonlocalto write to enclosing scope;globalto write to module scope.
def make_counter():
count = 0
def tick():
nonlocal count
count += 1
return count
return tick
Decorators
What it is. A function that wraps another function to add behavior. @deco is sugar for func = deco(func).
from functools import wraps
def timer(func):
@wraps(func)
def wrapper(*a, **kw):
# before
out = func(*a, **kw)
# after
return out
return wrapper
Key terms.
functools.wraps— preserves__name__/__doc__of original.- Decorator with args — three nested layers:
repeat(3) → decorator → wrapper. - Stacking — bottom-up:
@a / @b / def f→a(b(f)). - Built-ins —
@property,@staticmethod,@classmethod,@functools.lru_cache.
Generators and Iterators
What it is. Lazy producers. yield pauses and resumes; values produced on demand.
Key terms.
- Iterator protocol —
__iter__returns self,__next__returns next or raisesStopIteration. - Generator function — uses
yield. Generator expression —(x*x for x in it). yield from it— delegate to another iterable.send(val),close()— drive the generator from outside.
Remember. “Use generators for huge or infinite sequences — almost no memory.”
Built-in Functions
What it is. No-import helpers we use daily.
Key terms.
enumerate— index + value (with optionalstart).sorted(it, key=, reverse=)vslist.sort()— first returns new, second mutates in place.reversed,any,all(all([])isTrue!),isinstance,type.len,range,abs,round—round(2.5) == 2(banker’s rounding).min/max(..., key=)— works with any iterable.reprvsstr—reprfor devs (with quotes/escapes),strfor users.input()— always returns a string.
Object-Oriented Python
Classes and Objects
What it is. class Foo: with __init__(self, ...) to set instance state. self is automatic — current instance.
Key terms.
- Class attribute vs instance attribute — class attrs shared, instance attrs per-object.
__str__for users (used byprint);__repr__for devs (REPL/repr()).
Inheritance and MRO
What it is. Child borrows attrs/methods from parent. super().__init__(...) calls parent constructor.
Key terms.
- Multiple inheritance —
class D(B, C):. - Diamond problem — D inherits from B and C, both inherit from A. Whose method wins?
- C3 linearization — Python’s deterministic MRO. Inspect with
Cls.mro(). - Mixins — small classes adding focused behavior, combined via multiple inheritance.
Remember. MRO mantra: “Class itself first, then parents left-to-right, never visit a parent before all its children.”
Dunder (Magic) Methods
What it is. Hooks Python calls behind the scenes. They power +, len(), print(), in, with, for, etc.
Key terms.
- Identity / display —
__init__,__str__,__repr__,__hash__. - Comparison —
__eq__,__lt__,__gt__. Usefunctools.total_orderingto skip the rest. - Arithmetic —
__add__,__mul__,__sub__, … - Container —
__getitem__,__setitem__,__contains__,__len__,__iter__. - Callable —
__call__makes the instance callable like a function. - Context manager —
__enter__/__exit__.
Remember. Defining __eq__ without __hash__ makes the object unhashable (sets/dict keys break).
@staticmethod vs @classmethod
What it is. Three method types, distinguished by what they receive.
| Method | First arg | Use case |
|---|---|---|
| Instance | self | Read/modify instance state |
@classmethod | cls | Alternative constructors / factories |
@staticmethod | nothing | Utility functions namespaced under the class |
Remember. cls(...) in a classmethod respects subclasses; Pizza(...) would not.
Property Decorators
What it is. @property lets a method be accessed like a plain attribute, with getter/setter/deleter hooks.
class Person:
@property
def age(self): return self._age
@age.setter
def age(self, v):
if v < 0: raise ValueError
self._age = v
Remember. No-setter property = read-only computed attribute.
Abstract Classes and Interfaces
What it is. from abc import ABC, abstractmethod. Subclasses must implement abstract methods or instantiation raises TypeError.
Key terms.
- Concrete methods — abstract base classes can include normal methods that subclasses inherit.
- Abstract property — combine
@propertyand@abstractmethod. - Protocol — structural alternative; no inheritance required.
Remember. ABCs enforce a contract at instantiation time, not call time.
Dataclasses
What it is. @dataclass auto-generates __init__, __repr__, __eq__ from typed fields.
Key terms.
field(default_factory=list)— for mutable defaults.field(repr=False, compare=False)— exclude from auto-generated methods.@dataclass(frozen=True)— immutable & hashable.__post_init__— extra init logic after auto__init__.@dataclass(slots=True)(3.10+) — memory-efficient.- NamedTuple — immutable, tuple-like alternative for records.
Remember. “Stop hand-writing __init__. Use @dataclass.”
Scope & Memory
LEGB Scope Rule
What it is. Name lookup order: Local → Enclosing → Global → Built-in.
Key terms.
global x— write to module-levelxfrom inside a function.nonlocal x— write to enclosing function’sx.- UnboundLocalError — assigning to a name in a function makes it local; reading before assignment fails.
Remember. “L → E → G → B. First match wins.”
Shallow vs Deep Copy
What it is.
b = a— alias, same object.- Shallow copy —
copy.copy(a),a[:],list(a),a.copy(). New outer, shared inner refs. - Deep copy —
copy.deepcopy(a)— recursively duplicates everything.
Remember. Shallow copies of lists-of-lists share the inner lists.
Garbage Collection and Reference Counting
What it is. CPython frees memory primarily by reference counting. When refcount hits 0, the object is freed immediately.
Key terms.
sys.getrefcount(x)— current refcount (always +1 for the call).- Cycle problem — refcounting can’t free
a → b → acycles alone. - Generational GC — supplements refcounting; gen 0 (new) collected most often, gen 2 (old) least. Manually run with
gc.collect(). __del__— finalizer; rarely needed (use context managers instead).weakref— reference that doesn’t bump the refcount.
Global Interpreter Lock (GIL)
What it is. A mutex in CPython letting only one thread execute Python bytecode at a time. Exists to keep refcounting safe.
Impact.
- CPU-bound code — threads don’t help (or hurt). Use
multiprocessingor C extensions (NumPy releases GIL). - I/O-bound code — threads help; GIL is released during I/O waits.
Remember. “GIL = One Speaker At A Time.” Python 3.13 introduced experimental free-threaded mode (PEP 703).
Error Handling & Context
Exception Handling
What it is. try / except / else / finally blocks.
Key terms.
except SpecificError as e:— catch one type, bind toe.else— runs only if no exception (the happy path).finally— always runs (cleanup).raise— throw an exception.raise ... from e— chain causes.- Common builtins —
ValueError,TypeError,KeyError,IndexError,FileNotFoundError,AttributeError,ZeroDivisionError.
Remember. Bare except: is an anti-pattern — it catches KeyboardInterrupt and hides bugs.
Custom Exceptions
What it is. Subclasses of Exception for domain-specific errors.
Key terms.
- Inherit from
Exception(neverBaseException). - Hierarchy —
AppError→AuthError→PermissionDeniedError. Lets callers catch broadly or narrowly. - Custom attrs — attach
transaction_id,error_code, etc. - Naming — end with
Error. Always callsuper().__init__(message).
Context Managers
What it is. Objects used with with to guarantee setup/teardown. __enter__ returns the bound name, __exit__ cleans up — even on exceptions.
Key terms.
@contextmanagerdecorator — turn a generator into a context manager. Code beforeyieldis enter, after is exit.__exit__returningTruesuppresses the exception.- Typical uses — files, locks, DB connections,
tempfile.TemporaryDirectory,contextlib.suppress. - Stacking —
with open(a) as f, open(b) as g:for multiple managers.
from contextlib import contextmanager
@contextmanager
def timer():
import time
s = time.time()
yield
print(f"{time.time()-s:.2f}s")
Concurrency & Async
Threading vs Multiprocessing
What it is. Two ways to do work concurrently.
| Threading | Multiprocessing | |
|---|---|---|
| Memory | Shared (one process) | Separate (each process) |
| GIL | One global lock blocks parallelism | Each process has its own GIL → true parallel |
| Best for | I/O-bound (network, files) | CPU-bound (math, processing) |
| IPC | Direct via shared vars + locks | Queue, Pipe, Manager |
Remember. Multiprocessing scripts need if __name__ == "__main__": on Windows/macOS.
Asyncio and async/await
What it is. Single-threaded cooperative concurrency. async def defines a coroutine; await pauses it until the awaited thing settles. The event loop schedules.
Key terms.
asyncio.run(main())— entry point.asyncio.gather(*coros)— run concurrently, wait for all.asyncio.create_task(coro)— schedule in background; await later.- Cooperative vs preemptive — switches happen only at
awaitpoints (no surprise interleaving like threads).
Remember. “asyncio = waiter at many tables. One thread, many awaits.”
Concurrent.futures
What it is. High-level pool API. Same code can swap thread pool for process pool.
Key terms.
ThreadPoolExecutor— I/O-bound.ProcessPoolExecutor— CPU-bound.executor.map(fn, iterable)— bulk, results in submission order.executor.submit(fn, *args)— returns aFuture.f.result(),f.done(),f.cancel(),f.exception().as_completed(futures)— yields futures as they finish (fastest first).
Remember. “When you just want to parallelize a batch — reach here first.”
Advanced Python
Metaclasses
What it is. A metaclass is a class whose instances are classes. The default metaclass is type.
Key terms.
- Class creation chain —
type → MyMeta → MyClass → instance. - Custom metaclass —
class MyMeta(type): def __new__(mcs, name, bases, ns): .... Used by Django ORM, ABCs, plugin registries. __init_subclass__(3.6+) — simpler hook for subclass behavior. Prefer over metaclasses.
Remember. Tim Peters: “If you wonder whether you need a metaclass, you don’t.”
slots
What it is. __slots__ = ("x", "y") tells Python the only attributes a class will have. Skips per-instance __dict__.
Benefits. Less memory (matters at millions of instances), faster attribute access.
Trade-offs. No dynamic attributes. Inheritance is fiddly — define __slots__ in every subclass.
Remember. Use @dataclass(slots=True) (3.10+) — cleanest path.
Type Hints and Annotations
What it is. Optional annotations for params/returns/variables. Not enforced at runtime — used by IDEs and mypy.
Key terms.
- Modern syntax —
list[str],dict[str, int],tuple[float, float](3.9+). - Optional / Union —
str | None,str | int(3.10+). Old:Optional[str],Union[str, int]. TypeVar— generic functions:def first(xs: list[T]) -> T:.Protocol— structural typing.Callable[[int], str],Any, type aliases (type UserID = intin 3.12).
Walrus Operator and Modern Features
What it is. Recent quality-of-life additions.
Key terms.
- Walrus
:=(3.8) — assign-and-use in one expression:while (line := input()) != "quit":. - Positional-only
/(3.8) — params before/can’t be passed by keyword. match / case(3.10) — structural pattern matching: literals, typesint(n), sequences[a, *r], mappings{"k": v}, withifguards._is wildcard.X | Ytypes (3.10).except*ExceptionGroup (3.11) — handle groups of concurrent exceptions.- F-string nested quotes / multiline (3.12).
type Alias = ...statement (3.12).
Duck Typing and Protocols
What it is. “If it walks like a duck and quacks like a duck…” — Python cares what an object can do, not its class.
Key terms.
- EAFP (“Easier to Ask Forgiveness than Permission”) — try first, catch error. Pythonic.
- LBYL (“Look Before You Leap”) —
hasattrchecks. Less Pythonic. - Implicit protocols — Iterable, Callable, Context Manager, Hashable, Subscriptable.
typing.Protocol(3.8+) — formal structural typing without inheritance.@runtime_checkable— enableisinstance(obj, MyProtocol)at runtime.- Protocol vs ABC — Protocol = structural (just match shape); ABC = nominal (must inherit).
Remember. “Quack first, ask questions later.”
Modules & Patterns
Modules, Packages, and Imports
What it is. A module is a .py file. A package is a folder with __init__.py. Sub-packages nest.
Key terms.
import x,from x import y,from x import y as z. Avoidfrom x import *.- Absolute —
from myapp.models.user import User(preferred). - Relative —
from .utils import helper,from ..base import Foo. __init__.py— runs on import; can re-export for clean APIs;__all__controls*imports.- Circular imports — fix by extracting shared code, lazy importing inside a function, or restructuring.
if __name__ == "__main__":— block runs only when file is executed directly.
Pythonic Code and PEP 8
What it is. Community style + idioms. import this for the Zen.
Key idioms.
for i, x in enumerate(items):(notrange(len)).- Tuple unpack
x, y = pair. - EAFP over LBYL.
" ".join(words)for concatenation.- Truthy check
if my_list:(notif len(my_list) > 0:). - List comprehensions over manual loops.
Anti-patterns. type(x) == int (use isinstance), bare except:, mutable default args, gratuitous global, Java-style getters/setters.
File Handling and I/O
What it is. Always use with open(path, mode, encoding="utf-8") as f: — auto-closes.
Key terms.
- Modes —
r(read),w(overwrite),a(append),rb/wb(binary),r+(both). - Reading —
f.read(),f.readline(),f.readlines(), or iteratefor line in f:(best for large files). pathlib.Path— modern OO paths:p.exists(),p.suffix,p.read_text(),p / "sub" / "file".- JSON —
json.dump/dumps,json.load/loads. - CSV —
csv.reader,csv.writer(usenewline="").
Remember. Always pass encoding="utf-8" explicitly — defaults vary by OS.
Design Patterns in Python
What it is. Common patterns made simple by first-class functions and duck typing.
| Pattern | Pythonic implementation |
|---|---|
| Singleton | Module-level state (or __new__ override) |
| Factory | @classmethod alternative constructors |
| Observer | Callback dict + emit() |
| Strategy | Pass a function (no Strategy class needed) |
| Decorator | @deco syntax |
| Iterator | __iter__ + __next__ |
| Context Manager | __enter__ + __exit__ or @contextmanager |
Remember. Many classical patterns disappear because Python’s features cover them natively.
Common Output Questions
What it is. Classic Python interview gotchas.
- Mutable default arg —
def f(lst=[])shares one list across calls. Output:['a'], then['a', 'b']. - Late binding closures —
[lambda: i for i in range(3)]all return2. Fix:lambda i=i: i. - Integer caching —
isreturnsTruefor ints in[-5, 256],Falseoutside. Implementation detail; always use==. - String interning — short identifier-like strings interned, not “hello world”. Use
==. - List multiplication —
[[0]] * 3shares the inner list. Use[[0] for _ in range(3)]. - Exception variable scope —
einexcept ... as e:is deleted after the block. - Tuple with mutable element —
t = ([1,2],); t[0].append(3)works; the tuple’s reference didn’t change, the list inside did. - Chained comparisons —
1 < 2 < 3becomes1 < 2 and 2 < 3. Different from most languages. isvs==— same value vs same object. Two[1,2,3]lists are==but notis.
Remember. “Most gotchas come down to: object vs reference, and Python’s caching tricks.”