📡 You're offline — showing cached content
New version available!
Quick Access
Python Reference

Python 3

Core syntax, variables, lists, and common libraries.

All Topics

Syntax & Core Logic

Variables: int,str,float,bool
Python is dynamically typed. Variables are labels pointing to objects. Reassign any type freely.
Example: x = 10; x = "hello"; x = [1,2,3]
f-strings (f"...")
Fast string formatting with embedded expressions. Support format specs, conversion flags, nested braces.
Example: f"{price:.2f}" # "9.99" | f"{name!r}" # repr
Walrus operator :=
Assignment expression — assign AND use a value in one expression inside conditions/comprehensions.
Example: while (chunk := f.read(8192)): process(chunk)
match / case (3.10+)
Structural pattern matching. Matches values, types, sequences, mappings, and guard conditions.
Example: match cmd: case "quit": sys.exit() case ("go", d): move(d)
try / except / else / finally
else runs only if no exception. finally always runs. Catch specific exceptions, not bare except.
Example: try: r=db.query() except DBError as e: log(e) else: process(r) finally: db.close()
raise / raise from
Re-raise with context (raise ... from e) to chain exceptions. raise from None suppresses context.
Example: except KeyError as e: raise ValueError("Missing key") from e
assert statement
Debugging checks. Disabled when run with python -O. Never use for data validation in production.
Example: assert result > 0, f"Expected positive, got {result}"
global / nonlocal
global accesses module-level var. nonlocal accesses enclosing scope var in nested functions.
Example: def counter(): n=0; def inc(): nonlocal n; n+=1; return inc

Data Structures

List slicing [start:stop:step]
Negative indices count from end. Step -1 reverses. Slices return new lists (shallow copy).
Example: nums[::-1] # reverse | nums[::2] # every other | nums[-3:]
list.sort() vs sorted()
list.sort() mutates in-place. sorted() returns new list. Both accept key= and reverse= params.
Example: sorted(users, key=lambda u: (-u.score, u.name))
dict.get(k, default)
Safe key access with fallback. setdefault() sets AND returns default if key missing.
Example: count = d.get('x', 0); d.setdefault('key', []).append(1)
dict merge: {**a, **b} | a|b
Merge dicts with spread (3.5+) or | operator (3.9+). |= updates in-place.
Example: config = defaults | overrides # 3.9+
Set operations
& (intersect), | (union), - (difference), ^ (symmetric diff). Issubset/superset checks.
Example: common = set_a & set_b; only_a = set_a - set_b
collections.Counter
Dict subclass for counting hashable objects. most_common(n) returns top N elements.
Example: c = Counter("hello"); c.most_common(2) # [('l',2),('h',1)]
collections.defaultdict
Dict that auto-creates missing keys with a factory function — eliminates KeyError on first access.
Example: graph = defaultdict(list); graph['A'].append('B')
heapq module
Min-heap operations on a list. heappush/heappop in O(log n). nlargest/nsmallest for partial sort.
Example: heapq.heappush(h, (priority, task)); heapq.heappop(h)

Functional & Advanced

List comprehension
[expr for item in iter if cond] — faster than map/filter, reads like English.
Example: squares = [x**2 for x in range(10) if x % 2 == 0]
Dict / Set comprehension
Same syntax with {} — creates dict (k:v for ...) or set {v for ...}.
Example: word_len = {w: len(w) for w in words if len(w) > 3}
Generator expression
(expr for item in iter) — lazy evaluation, memory efficient, can only iterate once.
Example: total = sum(x**2 for x in range(1_000_000))
yield / yield from
Makes function a generator. yield from delegates to sub-generator, flattening the iteration.
Example: def flatten(lst): yield from (x if not isinstance(x,list) else flatten(x) for x in lst)
@functools.lru_cache
Memoize function results. maxsize=None = unlimited. @cache is simpler alias (Python 3.9+).
Example: @cache def fib(n): return n if n < 2 else fib(n-1)+fib(n-2)
functools.partial
Create new function with some arguments pre-filled — reusable configured callables.
Example: double = partial(mul, 2); pow2 = partial(pow, exp=2)
itertools.chain/product/groupby
Powerful iterator building blocks — chain iterables, cartesian products, consecutive group detection.
Example: for k, g in groupby(sorted_data, key=lambda x: x.dept): ...
operator module
Functions for all operators (add, itemgetter, attrgetter) — faster than lambda in sort keys.
Example: from operator import attrgetter; sorted(objs, key=attrgetter('name'))

OOP & Dataclasses

@dataclass
Auto-generates __init__, __repr__, __eq__. frozen=True makes it immutable. order=True adds comparison.
Example: @dataclass(frozen=True, order=True) class Point: x: float; y: float
__slots__
Declare allowed attributes — saves 40-50% memory vs __dict__, faster attribute access.
Example: class Vector: __slots__ = ('x', 'y'); def __init__(self,x,y): self.x=x; self.y=y
__dunder__ methods
Magic methods for operator overloading and protocol implementation.
Example: __add__ __len__ __iter__ __contains__ __enter__ __exit__ __call__
@property / @setter
Define computed attributes with validation. Access like attribute, not method call.
Example: @property def age(self): return self._age @age.setter def age(self, v): assert v>=0; self._age=v
Abstract Base Classes
from abc import ABC, abstractmethod — enforce interface/method contracts in subclasses.
Example: class Shape(ABC): @abstractmethod def area(self) -> float: ...
Protocol (structural typing)
Define interface without inheritance — duck typing with static analysis support (3.8+).
Example: class Drawable(Protocol): def draw(self) -> None: ...
__init_subclass__
Hook called when a class is subclassed — plugin registration, automatic class modification.
Example: class Plugin(Base): def __init_subclass__(cls, **kw): REGISTRY[cls.name] = cls

Async & Concurrency

asyncio.gather()
Run multiple coroutines concurrently and collect results — equivalent to Promise.all.
Example: results = await asyncio.gather(task1(), task2(), return_exceptions=True)
asyncio.create_task()
Schedule coroutine to run "in background" without awaiting immediately.
Example: task = asyncio.create_task(fetch(url)); do_other_work(); await task
asyncio.timeout() (3.11+)
Context manager for async timeouts — replaces asyncio.wait_for with cleaner syntax.
Example: async with asyncio.timeout(5.0): await slow_operation()
ThreadPoolExecutor
Run blocking I/O in threads alongside async code using loop.run_in_executor.
Example: result = await loop.run_in_executor(None, blocking_db_call, args)
multiprocessing.Pool
CPU-bound parallel processing — bypasses GIL using separate processes.
Example: with Pool(os.cpu_count()) as p: results = p.map(process, data_chunks)
concurrent.futures
High-level interface for thread/process pools with Future objects.
Example: with ProcessPoolExecutor() as ex: futs = [ex.submit(fn, x) for x in data]

Standard Library & Type Hints

pathlib.Path
Modern OO path handling. Operators like / for joining. Built-in read/write text methods.
Example: p = Path("data") / "file.csv"; text = p.read_text(encoding='utf-8')
contextlib.contextmanager
Create context managers with a generator function and yield. No need to write __enter__/__exit__.
Example: @contextmanager def timer(): t=time.time(); yield; print(time.time()-t)
dataclasses.field()
Fine-grained control over dataclass fields — defaults, factories, metadata, exclusion from repr/compare.
Example: tags: list = field(default_factory=list, repr=False)
typing.TypeVar / Generic
Create generic classes and functions that work with any type while maintaining type safety.
Example: T = TypeVar('T'); def first(lst: list[T]) -> T: return lst[0]
typing.overload
Declare multiple type signatures for a function that behaves differently based on argument types.
Example: @overload def process(x: int) -> int: ... @overload def process(x: str) -> str: ...
__all__ in modules
Controls what names are exported with "from module import *". Documents public API explicitly.
Example: __all__ = ['PublicClass', 'public_func'] # _private not exported
importlib / __import__
Dynamic imports at runtime — plugin systems, optional dependencies, conditional imports.
Example: mod = importlib.import_module(f'plugins.{name}')