← Back to Python

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.

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.

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.

Remember. “Strings don’t mutate. Capture the return value.”

Lists, Tuples, and Sets

What it is. Three core collection types.

TypeOrderedMutableDuplicatesHashable
list []yesyesyesno
tuple ()yesnoyesyes (if all elements hashable)
set {}noyesnono

Key terms.

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.

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.

Remember.name = user_input or 'Anonymous'.”

Functions

Functions and Arguments

What it is. def name(params):. Implicit return None if not specified.

Key terms.

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.

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.

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.

Generators and Iterators

What it is. Lazy producers. yield pauses and resumes; values produced on demand.

Key terms.

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.

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.

Inheritance and MRO

What it is. Child borrows attrs/methods from parent. super().__init__(...) calls parent constructor.

Key terms.

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.

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.

MethodFirst argUse case
InstanceselfRead/modify instance state
@classmethodclsAlternative constructors / factories
@staticmethodnothingUtility 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.

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.

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.

Remember. “L → E → G → B. First match wins.”

Shallow vs Deep Copy

What it is.

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.

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.

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.

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.

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.

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.

ThreadingMultiprocessing
MemoryShared (one process)Separate (each process)
GILOne global lock blocks parallelismEach process has its own GIL → true parallel
Best forI/O-bound (network, files)CPU-bound (math, processing)
IPCDirect via shared vars + locksQueue, 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.

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.

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.

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.

Walrus Operator and Modern Features

What it is. Recent quality-of-life additions.

Key terms.

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.

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.

Pythonic Code and PEP 8

What it is. Community style + idioms. import this for the Zen.

Key idioms.

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.

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.

PatternPythonic implementation
SingletonModule-level state (or __new__ override)
Factory@classmethod alternative constructors
ObserverCallback dict + emit()
StrategyPass 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.

Remember. “Most gotchas come down to: object vs reference, and Python’s caching tricks.”