PrepStack › Backend › Python

Python interview cheat sheet

Data model, functions, generators, OOP, GIL, asyncio and output puzzles

Python interviews test whether you understand how the language really works, not just its syntax: names vs objects, mutability, scope and closures, decorators, generators, the object model and MRO, and why the GIL matters for concurrency. Expect a few "what does this print?" puzzles too. Read the 15-minute revision first, run through the sections from basics to advanced, then switch to Quiz mode and answer out loud. Runnable snippets are verified on Python 3.9; newer syntax (3.10+) is shown without output.

15-minute revision

  1. Everything is an object with an identity (id), a type and a value. Variables are names bound to objects; the type lives on the object, not the name (dynamic + strong typing).
  2. == compares values (__eq__); is compares identity. Use is only for singletons: x is None. CPython caches small ints -5..256, so is on ints is unreliable.
  3. Immutable: int float bool str tuple frozenset bytes None. Mutable: list dict set bytearray and most user objects. A tuple holding a list is still mutable inside.
  4. Python passes object references by value ("call by sharing"): mutating an argument is visible to the caller, rebinding it is not.
  5. list index/append O(1), insert(0)/pop(0)/in O(n). dict/set lookup, insert and in are O(1) average (hash tables). Use deque for queues.
  6. Dicts keep insertion order (guaranteed since 3.7). Keys must be hashable; equal objects must have equal hashes (1, 1.0, True are the same key).
  7. copy.copy / list.copy() / slicing make shallow copies (inner objects shared). copy.deepcopy copies recursively and handles cycles.
  8. Mutable default arguments are evaluated once, at def time, and shared across calls. Use None as the default and create the object inside.
  9. Name lookup is LEGB: Local → Enclosing → Global → Built-in. Assigning makes a name local unless declared global/nonlocal. Closures bind late (by variable, not value).
  10. A decorator is a callable that takes a function and returns a replacement. Decorators with arguments are factories (three levels). Always use functools.wraps.
  11. Generators (yield) are lazy iterators that keep their frame between calls. Iterator protocol: __iter__ returns the iterator, __next__ returns items and raises StopIteration.
  12. with calls __enter__/__exit__; __exit__ always runs, and returning True from it swallows the exception. @contextlib.contextmanager builds one from a generator.
  13. @classmethod gets cls (alternative constructors), @staticmethod gets nothing (namespaced helper), @property makes a computed/validated attribute.
  14. MRO uses C3 linearization (Cls.__mro__). super() calls the next class in the MRO, not necessarily the parent — this enables cooperative multiple inheritance.
  15. The GIL lets only one thread run Python bytecode at a time: threads help with I/O, not CPU. Use multiprocessing for CPU work and asyncio for many concurrent I/O tasks. 3.13 added an experimental free-threaded build; 3.14 made it officially supported (still optional).
  16. CPython frees objects by reference counting (immediately at zero) plus a cyclic garbage collector for reference cycles. Type hints are not enforced at runtime.

Data model & built-in types

Objects, names, dynamic typing & is vs ==

Every value is an object; variables are just names (labels) pointing at objects.

  • Every object has an identity (id(), its address in CPython), a type (type()) and a value. Identity and type never change after creation.
  • Dynamic typing: a name can be rebound to an object of any type. Strong typing: Python will not silently convert '1' + 1; it raises TypeError.
  • Functions, classes, modules and even types are objects: you can pass them around, store them in dicts and add attributes. type(int) is type.
  • Assignment never copies. b = a binds a second name to the same object.
  • == calls __eq__ (value equality). is checks identity (same object). x is None is the idiomatic None check because None is a singleton.
  • CPython caches ints from -5 to 256 and interns many identifier-like strings, so is may look like it works on small values. It is an implementation detail; never rely on it.

Interview questions

  • Is Python statically or dynamically typed? Strongly or weakly?
  • Difference between is and ==?
  • Why does a is b return True for 100 but False for 1000?
  • What does "everything is an object" mean in practice?

Mutable vs immutable & shallow vs deep copy

Immutable objects can't change in place; mutable ones can, and every name sharing them sees the change.

  • Immutable: int, float, bool, str, bytes, tuple, frozenset, None. Operations return new objects.
  • Mutable: list, dict, set, bytearray, most class instances. Methods like append change the object in place and return None.
  • Immutability is shallow: a tuple of lists cannot get new slots, but the lists inside can change. Such a tuple is also not hashable.
  • Call by sharing: functions receive references. Mutating a parameter is visible to the caller; rebinding the parameter is local.
  • += is in-place for mutable types (list.__iadd__) but creates a new object for immutable ones. Other names pointing at the list see the change.
  • Shallow copy (lst.copy(), lst[:], list(lst), dict(d), copy.copy) makes a new outer container that shares the inner objects. Deep copy (copy.deepcopy) copies recursively and uses a memo dict so cycles work.

Interview questions

  • Which built-in types are mutable and which are immutable?
  • Is Python pass-by-value or pass-by-reference?
  • Difference between shallow and deep copy?

list, tuple, set, dict & time complexity

Pick the container by the operation you do most: index → list, membership/lookup → set/dict, both ends → deque.

  • list: dynamic array of references. Fast index and append at the end; inserting or deleting at the front shifts every element.
  • tuple: immutable sequence. Slightly smaller and faster to create, hashable when its items are, used for fixed records and dict keys.
  • set / frozenset: hash table of unique, hashable items. O(1) average membership; supports | & - ^ set algebra. No order.
  • dict: hash table from hashable keys to values. Keeps insertion order (3.7+). d.get(k, default), setdefault, and | merge (3.9+).
  • collections: deque (O(1) both ends), Counter (multiset), defaultdict (auto-create missing values), OrderedDict (move_to_end, order-aware equality), namedtuple. heapq gives a min-heap on a list.
  • Strings are immutable: building with += in a loop can be O(n²). Collect pieces in a list and ''.join(parts).

Interview questions

  • Difference between a list and a tuple?
  • Why is x in some_set faster than x in some_list?
  • How would you implement a queue or a LRU cache in Python?

Functions, scope & decorators

Arguments: *args, **kwargs & the mutable default trap

Parameters go: positional-only /, normal, *args, keyword-only, **kwargs — and defaults are evaluated once.

  • Order in a signature: def f(pos_only, /, normal, *args, kw_only, **kwargs). A bare * forces the following parameters to be keyword-only.
  • *args collects extra positional arguments into a tuple; kwargs collects extra keyword arguments into a dict**.
  • At the call site, *iterable unpacks into positional arguments and **mapping into keyword arguments.
  • Positional-only parameters (/, 3.8+) let you rename them later without breaking callers; many built-ins like len(obj, /) use them.
  • Default values are evaluated once, when def runs, and stored in func.__defaults__. A mutable default ([], {}) is therefore shared between calls.
  • Fix: default to None (or a private sentinel object) and create the new object inside the function.

Interview questions

  • What are *args and **kwargs?
  • Explain the mutable default argument problem.
  • What do / and a bare * mean in a signature?

LEGB scope, closures, global & nonlocal

Names resolve Local → Enclosing → Global → Built-in, decided at compile time by where you assign.

  • LEGB: a name is searched in the Local function scope, then Enclosing function scopes, then the module's Global scope, then builtins.
  • Scope is decided at compile time: if a function assigns to a name anywhere in its body, that name is local everywhere in the function. Reading it before the assignment raises UnboundLocalError.
  • global name rebinds a module-level name; nonlocal name rebinds a name in the nearest enclosing function. Neither is needed just to mutate an object.
  • A closure is an inner function that remembers variables from its enclosing scope, stored in cells (fn.__closure__). Each call of the outer function creates fresh cells.
  • Closures bind late: they look up the variable when called, not when created. Lambdas built in a loop all see the loop variable's final value.
  • Classes do not create an enclosing scope for their methods: inside a method, use self.x or ClassName.x, not bare x.

Interview questions

  • What is the LEGB rule?
  • Difference between global and nonlocal?
  • What is a closure and where is it used?
  • Why does [lambda: i for i in range(3)] return 2, 2, 2?

Decorators (with arguments, functools.wraps)

@deco above def f is just f = deco(f): a function that wraps another to add behaviour.

  • @deco is syntactic sugar for f = deco(f). The decorator runs once, at definition time; the wrapper runs on every call.
  • A typical wrapper takes *args, **kwargs, does something before/after, calls the original and returns its result.
  • Decorator with arguments = a factory: @retry(times=3) calls retry(times=3), which returns the real decorator. That gives three nested levels.
  • functools.wraps(func) copies __name__, __doc__, __module__, __qualname__, __dict__ and sets __wrapped__. Without it, logs, docs and introspection show wrapper.
  • Stacked decorators apply bottom-up (the one nearest def wraps first) and run top-down at call time.
  • Built-in decorators you should know: @property, @classmethod, @staticmethod, @functools.lru_cache / @functools.cache (3.9), @dataclass, @contextmanager, @functools.singledispatch.

Interview questions

  • What is a decorator and how does it work?
  • How do you write a decorator that takes arguments?
  • Why use functools.wraps?
  • In which order do stacked decorators run?

Iterators, generators, yield & comprehensions

An iterator hands out items one at a time; a generator is the easy way to write one, and comprehensions are the concise way to build collections.

  • Iterable: has __iter__ returning an iterator (list, dict, str, file). Iterator: has __next__ and __iter__ returning itself; raises StopIteration when done. for calls iter() then next() until StopIteration.
  • Iterators are single-use; iterables can usually be iterated many times because each iter() gives a fresh iterator.
  • A function containing yield is a generator function. Calling it returns a generator object; the body runs only on next() and pauses at each yield, keeping local state.
  • yield from sub delegates to a sub-iterator (and forwards send/throw). gen.send(v) resumes the generator and makes yield evaluate to v.
  • Comprehensions: list [...], set {...}, dict {k: v ...}, and generator expressions (...). Generator expressions are lazy and use constant memory.
  • itertools gives lazy building blocks: chain, islice, groupby, count, cycle, product, accumulate, tee.

Interview questions

  • Difference between an iterable and an iterator?
  • What is a generator and why use one?
  • What does yield from do?
  • How do you process a 50 GB log file in Python?

Errors & resources

Exceptions: try/except/else/finally, custom errors, chaining

Catch specific exceptions, put the happy path in else, cleanup in finally, and chain with raise ... from.

  • try → except (handles matching errors, first match wins) → else (runs only if no exception) → finally (always runs, even on return or break).
  • Hierarchy: BaseException → Exception → most errors. KeyboardInterrupt, SystemExit and GeneratorExit inherit from BaseException directly, so except Exception does not catch them.
  • Custom exceptions subclass Exception (often a base AppError for your package). Add fields for context.
  • raise NewError(...) from err sets __cause__ (explicit chain). Raising inside an except without from sets __context__ (implicit). from None hides the chain.
  • EAFP ("easier to ask forgiveness than permission": try and catch) is the Pythonic style; LBYL (check first) can race with other threads or processes.
  • 3.11 added exception groups and except* for raising/handling several errors at once (used by asyncio.TaskGroup), plus err.add_note().

Interview questions

  • What is the purpose of else and finally in try statements?
  • Difference between Exception and BaseException?
  • What does raise ... from ... do?
  • EAFP vs LBYL?

Context managers & the with statement

with guarantees setup and teardown: __enter__ on the way in, __exit__ on the way out, even on errors.

  • with expr as x: calls expr.__enter__() and binds its return value to x. On exit it calls __exit__(exc_type, exc, tb) — with Nones if no exception.
  • If __exit__ returns a truthy value, the exception is suppressed. Return False/None to let it propagate.
  • @contextlib.contextmanager turns a generator into a context manager: code before yield is setup, after it is teardown. Wrap the yield in try/finally so teardown runs on errors.
  • Common ones: files, threading.Lock, DB connections/transactions, decimal.localcontext, unittest.mock.patch, tempfile.TemporaryDirectory.
  • contextlib also has suppress, closing, nullcontext, redirect_stdout, ExitStack (dynamic number of managers) and async versions (asynccontextmanager, async with).
  • Multiple managers: with a() as x, b() as y:. Parenthesised multi-line form is official from 3.10.

Interview questions

  • What is a context manager?
  • How can a context manager suppress an exception?
  • How would you write a timing context manager?

Object-oriented Python

Classes, attributes, @classmethod, @staticmethod & @property

Instance methods get self, class methods get cls, static methods get nothing, and properties look like attributes but run code.

  • __init__ initialises an already-created object; __new__ actually creates it (needed for immutable subclasses and singletons).
  • Class attributes live on the class and are shared; instance attributes live in obj.__dict__. Lookup checks the instance first, then the class (and its MRO).
  • Assigning obj.attr = v always writes to the instance, so it shadows the class attribute rather than changing it. A mutable class attribute (items = []) is shared by all instances — a classic bug.
  • @classmethod receives the class: perfect for alternative constructors (from_json) that also work for subclasses. @staticmethod is a plain function grouped in the class.
  • @property gives getter/setter/deleter logic behind attribute syntax, so you can add validation later without changing callers.
  • Privacy is by convention: _name means internal. __name triggers name mangling to _ClassName__name to avoid clashes in subclasses; it isn't real security.

Interview questions

  • Difference between @classmethod and @staticmethod?
  • Difference between __new__ and __init__?
  • Does Python have private members?

Dunder methods & the data model

Special __methods__ let your objects plug into built-in syntax: printing, comparison, arithmetic, len, in, iteration and calls.

  • __repr__ is the unambiguous developer view (used by the REPL and containers); __str__ is the friendly view used by print and str(). If only __repr__ exists, str() falls back to it.
  • __eq__ and __hash__ go together: defining __eq__ sets __hash__ to None (unhashable) unless you define it. Equal objects must have equal hashes; hash only immutable fields.
  • Return NotImplemented (not False) from binary methods for unknown types so Python can try the reflected method (__radd__, the other side's __eq__).
  • Container protocol: __len__, __getitem__, __setitem__, __contains__, __iter__. __bool__ (or __len__) controls truthiness.
  • __call__ makes instances callable; __enter__/__exit__ make context managers; __getattr__ runs only for missing attributes while __getattribute__ runs for all.
  • functools.total_ordering fills in the remaining comparisons from __eq__ plus one of __lt__/__le__/__gt__/__ge__.

Interview questions

  • Difference between __str__ and __repr__?
  • If you override __eq__, what else must you think about?
  • Difference between __getattr__ and __getattribute__?

Inheritance, MRO, super() & abstract classes

Python supports multiple inheritance; C3 linearization gives one consistent lookup order and super() follows it.

  • Attribute lookup walks the Method Resolution Order: Cls.__mro__ / Cls.mro(). Every class ultimately ends in object.
  • The MRO is computed with C3 linearization: children come before parents, and the left-to-right order of bases is kept. If no such order exists, class creation fails with TypeError.
  • super() returns a proxy for the next class after the current one in the MRO of type(self), not simply the parent. In a diamond, A's super() may call B.
  • Cooperative multiple inheritance: every class in the chain calls super().method(**kwargs) so each one runs exactly once.
  • Mixins are small classes adding one capability (JsonMixin, LoggingMixin); list them before the main base.
  • abc.ABC + @abstractmethod creates an abstract base class: you can't instantiate it until all abstract methods are overridden. For structural (duck) typing without inheritance, use typing.Protocol.

Interview questions

  • What is MRO and how is it computed?
  • How does super() work with multiple inheritance?
  • Abstract base class vs Protocol?
  • When would class creation fail because of the MRO?

dataclasses, NamedTuple, Enum & __slots__

Let the standard library write boilerplate: @dataclass for records, NamedTuple for immutable tuples, Enum for constants, __slots__ for memory.

  • @dataclass generates __init__, __repr__ and __eq__ from type-annotated fields. Options: order=True (comparisons), frozen=True (immutable + hashable). 3.10 added slots=True and kw_only=True.
  • Mutable defaults must use field(default_factory=list); a plain = [] raises ValueError at class creation (dataclasses protect you from the shared-default bug).
  • __post_init__ runs after the generated __init__ for validation or derived fields. dataclasses.asdict/replace help with conversion and copies.
  • typing.NamedTuple is an immutable tuple subclass with named fields: lightweight, hashable, unpackable.
  • Enum gives named, unique, comparable-by-identity constants; members are singletons (Color.RED is Color['RED']). Use IntEnum/StrEnum (3.11) when they must act like ints/strings.
  • __slots__ = ('x', 'y') replaces the per-instance __dict__ with fixed slots: less memory and slightly faster attribute access, but no new attributes at runtime and no __dict__ unless listed.

Interview questions

  • What does @dataclass generate and when would you use it?
  • What are __slots__ and their trade-offs?
  • dataclass vs NamedTuple vs Pydantic model?

Concurrency & runtime internals

GIL: threading vs multiprocessing vs asyncio

The GIL lets one thread run Python bytecode at a time: threads for I/O, processes for CPU, asyncio for huge numbers of I/O waits.

  • The Global Interpreter Lock is a mutex in (standard) CPython that only one thread can hold while executing bytecode. It keeps reference counting and interpreter internals simple and fast for single-threaded code.
  • Threads release the GIL during blocking I/O and inside many C extensions (NumPy, hashlib, zlib), so threads still speed up I/O-bound work. CPU-bound pure-Python threads take turns (switch interval ~5 ms) and don't run in parallel.
  • The GIL does not make your code thread-safe: counter += 1 is several bytecodes, so updates can be lost. Use Lock, queue.Queue or other synchronisation.
  • multiprocessing / ProcessPoolExecutor: separate processes, each with its own interpreter and GIL → true CPU parallelism. Costs: process start-up, pickling arguments and results, more memory.
  • asyncio: one thread, an event loop and cooperative coroutines. Scales to thousands of concurrent sockets with low overhead, but any blocking call freezes everything.
  • Free-threaded CPython (PEP 703): experimental build in 3.13 (python3.13t), officially supported but still optional in 3.14 (PEP 779). It removes the GIL so threads run in parallel, at some single-threaded cost and with C-extension compatibility work. Other interpreters: PyPy and older Jython/IronPython differ.

Interview questions

  • What is the GIL and why does CPython have it?
  • If there's a GIL, why use threads at all?
  • Threading vs multiprocessing vs asyncio — how do you choose?
  • Does the GIL make Python code thread-safe?

asyncio basics: coroutines, tasks & the event loop

async def makes a coroutine, await yields control to the event loop, and tasks run coroutines concurrently on one thread.

  • async def f() returns a coroutine object when called; nothing runs until it is awaited or scheduled. asyncio.run(main()) creates the event loop, runs main and closes the loop.
  • await x suspends the current coroutine until x (a coroutine, Task or Future) completes, letting the loop run other ready tasks.
  • asyncio.create_task(coro) schedules a coroutine to run concurrently and returns a Task. Keep a reference to it — the loop holds only weak references, so a forgotten task can be garbage-collected.
  • asyncio.gather(*aws) runs awaitables concurrently and returns results in order. 3.11's asyncio.TaskGroup (async with) is the structured, safer alternative: if one task fails, the rest are cancelled.
  • Timeouts: asyncio.wait_for(aw, timeout) or async with asyncio.timeout(s) (3.11+). Cancellation raises CancelledError inside the task — don't swallow it.
  • Never call blocking code (time.sleep, requests.get, heavy CPU) inside a coroutine. Use async libraries (httpx, aiohttp, asyncpg) or offload with await asyncio.to_thread(func) (3.9+).

Interview questions

  • How does asyncio achieve concurrency on a single thread?
  • Difference between a coroutine, a Task and a Future?
  • asyncio.gather vs TaskGroup?
  • What happens if you call time.sleep(1) inside a coroutine?

Memory management: reference counting & garbage collection

CPython frees most objects instantly via reference counting; a cyclic GC cleans up reference cycles that refcounting can't.

  • Each object has a reference count. It goes up on assignment, being put in a container or passed as an argument, and down when references go away. At zero the object is freed immediately (deterministic).
  • Reference counting can't free cycles (a.other = b; b.other = a). The cyclic garbage collector (gc module) periodically finds groups of container objects reachable only from each other and frees them.
  • The GC is generational: new objects are scanned often, survivors less often, based on allocation thresholds. 3.14 made collection incremental to shorten pauses. gc.collect() forces a full run; gc.disable() turns off only the cycle collector.
  • weakref.ref / WeakValueDictionary refer to an object without increasing its refcount — good for caches and observer lists.
  • Small objects come from pymalloc (arenas → pools → blocks), so freed memory is often reused by Python rather than returned to the OS; process RSS may not shrink.
  • Leak hunting: tracemalloc (snapshot diff), gc.get_referrers, objgraph; usual culprits are growing global caches, unbounded lru_cache, and listeners/closures holding big objects.

Interview questions

  • How does Python manage memory?
  • Why does Python need a garbage collector if it has reference counting?
  • How would you find a memory leak in a long-running Python service?

Typing, tooling, versions & puzzles

Type hints & the typing module

Hints document intent and power static checkers and IDEs; the interpreter doesn't enforce them.

  • Annotations (def f(x: int) -> str) are stored in __annotations__ and ignored at runtime. Tools like mypy and pyright check them; frameworks like FastAPI and Pydantic read them to validate data.
  • Since 3.9, use built-in generics: list[int], dict[str, int], tuple[int, ...]. Since 3.10, write unions as int | None instead of Optional[int] / Union[int, None].
  • Key tools: Optional, Union, Any, Callable[[int], str], Literal['r', 'w'], Final, ClassVar, TypedDict (typed dict shapes), Protocol (structural typing), TypeVar/Generic for generics.
  • 3.12 added PEP 695 syntax: def first[T](xs: list[T]) -> T and type Vector = list[float]. typing.Self (3.11) types fluent methods and alternative constructors.
  • Forward references: quote the name ('Node') or from __future__ import annotations. 3.14 evaluates annotations lazily by default (PEP 649/749), so forward references just work.
  • Gradual typing: start at boundaries (public functions), run the checker in CI, and avoid overusing Any, which switches checking off.

Interview questions

  • Are type hints enforced at runtime?
  • Difference between Protocol and an abstract base class?
  • Optional[int] — does it mean the argument is optional?

Modules, packages, venv & pip

A module is a .py file, a package is a directory of modules, and each project gets its own virtual environment.

  • A module is a .py file; importing it runs its top-level code once and caches it in sys.modules. Later imports reuse the cached module.
  • A package is a directory of modules, usually with __init__.py (runs on import, defines the package API). Without it you get a namespace package.
  • if __name__ == '__main__': runs code only when the file is executed directly, not when imported. python -m pkg.mod runs a module as a script with correct package imports.
  • Import search order: sys.path = script's directory (or cwd), PYTHONPATH, the standard library, then site-packages. Shadowing a stdlib name (your own random.py) is a common bug.
  • Virtual environments (python -m venv .venv) isolate each project's interpreter and packages. pip install puts packages into the active environment's site-packages.
  • Modern projects declare metadata and dependencies in pyproject.toml, pin with lock files (requirements.txt via pip-tools, Poetry, or uv), and run tools like ruff (lint/format), mypy/pyright, and pytest.

Interview questions

  • Difference between a module and a package?
  • What does if __name__ == '__main__' do?
  • Why use a virtual environment?

What's new: Python 3.10 → 3.15

Know the headline feature of each recent release; interviewers use them to see if you keep up.

  • 3.10: structural pattern matching (match/case), X | Y union types, parenthesised context managers, zip(strict=True), much better error messages.
  • 3.11: Faster CPython — 10–60% faster than 3.10 (about 1.25× on average) via the specialising adaptive interpreter; exception groups + except*; asyncio.TaskGroup; tomllib; typing.Self; fine-grained error locations.
  • 3.12: PEP 695 generics syntax and type aliases; f-strings formalised (PEP 701: reuse quotes, multi-line, comments); per-interpreter GIL; @typing.override; inlined comprehensions; distutils removed.
  • 3.13: new interactive REPL (colours, multi-line editing); experimental free-threaded build (no GIL, PEP 703); experimental JIT (PEP 744); dead batteries removed (cgi, telnetlib...; PEP 594); defined locals() semantics (PEP 667).
  • 3.14 (Oct 2025): deferred evaluation of annotations (PEP 649/749); template strings t'...' (PEP 750); subinterpreters in the stdlib (PEP 734); except A, B: without brackets (PEP 758); free-threaded build officially supported (PEP 779); compression.zstd; return/break in finally now warn (PEP 765).
  • 3.15 (Oct 2026): explicit lazy imports (lazy import json, PEP 810), frozendict built-in, UTF-8 as the default encoding (PEP 686), unpacking in comprehensions (PEP 798), a sampling profiler. 3.9 reached end-of-life in October 2025.

Interview questions

  • What is structural pattern matching and how is it different from a switch?
  • Why was Python 3.11 so much faster?
  • What are t-strings in Python 3.14?

Common output puzzles

Most "what does this print?" questions test aliasing, late binding, scope, defaults, finally, or hashing equality.

  • [[0] * 3] * 3 repeats the same inner list three times; use a comprehension to make independent rows.
  • Removing items from a list while iterating it skips elements, because the index keeps moving forward while items shift left.
  • round() uses banker's rounding (half to even): round(2.5) == 2. // floors toward negative infinity: 7 // -2 == -4; % takes the sign of the divisor.
  • Comparisons chain: a < b < c means a < b and b < c, so False == False in [False] is True.
  • A return in finally overrides the try's return and swallows exceptions (3.14 emits a SyntaxWarning).
  • Functions look up globals when they run, not when defined. (1) is just 1; a one-item tuple needs a comma: (1,).

Interview questions

  • What does [[0] * 3] * 3 produce and what's the bug?
  • Why does round(2.5) return 2?
  • What does a function with return in both try and finally return?