Skip to content

Python — Basics

  • Versions: Python 3.13 introduced experimental free-threaded build (PEP 703, no GIL). Default builds still have GIL.
  • Mutable vs immutable: list/dict/set mutable; tuple/str/int/frozenset immutable. Mutable default args = classic bug (def f(x=[])).
  • Truthiness: 0, 0.0, "", [], {}, None, False are falsy.
  • Comprehensions: list [x for x in xs], dict {k: v for ...}, set {x for ...}, generator (x for ...).
  • is vs ==: is checks identity (same object), == checks equality. Use is None, is True.
  • String formatting: f-strings (3.6+), .format(), % (legacy).
Oplistdictsetdeque
indexO(1)O(n)
appendO(1) amort.O(1)
pop endO(1)O(1)
pop frontO(n)O(1)
lookupO(n)O(1)O(1)O(n)
insert midO(n)O(n)
  • defaultdict(list), Counter, deque, OrderedDict (dicts ordered since 3.7), namedtuple, ChainMap.
  • First-class objects. Decorators wrap functions: @decorator = f = decorator(f).
  • *args / **kwargs. Keyword-only args after *.
  • Lambdas: single expression. Use def for anything else.
  • Closures capture by reference, not value (late binding gotcha in loops).
  • Classes: class Foo:. __init__ is constructor, __new__ allocator (rarely overridden).
  • Dunder methods: __repr__, __str__, __eq__, __hash__, __lt__, __enter__/__exit__ (context mgr), __iter__/__next__.
  • Inheritance: MRO (Method Resolution Order) via C3 linearization. super() follows MRO.
  • Dataclasses (3.7+): @dataclass auto-generates __init__, __repr__, __eq__. Use frozen=True for immutability.
  • __slots__: restrict attrs, save memory (no __dict__).
  • Abstract base classes: from abc import ABC, abstractmethod.
  • Hierarchy: BaseExceptionException → … Catch Exception, never bare except: (catches KeyboardInterrupt).
  • try/except/else/finally. else runs only if no exception.
  • Custom: class MyError(Exception): ....
  • Raise from: raise NewError(...) from original.
  • with (context manager) for resource cleanup.
  • iter(obj) → iterator. next(it) → next value or StopIteration.
  • yield makes function a generator. Lazy, memory-efficient.
  • yield from delegates.
  • async def + await. asyncio.run(main()) to start.
  • asyncio.gather, asyncio.create_task, asyncio.wait_for(coro, timeout).
  • Don’t call blocking I/O inside async — use async libs (aiohttp, asyncpg, motor).
  • loop.run_in_executor(None, blocking_fn) to offload blocking work.
  • Optional but heavily used in modern code. Checked by mypy, pyright.
  • from typing import Optional, Union, Callable, TypeVar, Generic, Protocol.
  • 3.10+: X | Y (union shorthand), match/case (structural pattern matching).
  • 3.12+: PEP 695 generics syntax — def f[T](x: T) -> T: ....
  • Django — batteries-included; ORM, admin, auth, migrations.
  • Flask — micro, WSGI.
  • FastAPI — async, Pydantic, OpenAPI auto, ASGI. Modern default for new APIs.
  • pip, venv, pip-tools, poetry, uv (fast modern installer/resolver).
  • Format: black, ruff format. Lint: ruff, flake8. Type: mypy, pyright.
  • Test: pytest, unittest. Coverage: coverage.py.