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
- 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). ==compares values (__eq__);iscompares identity. Useisonly for singletons:x is None. CPython caches small ints -5..256, soison ints is unreliable.- Immutable:
int float bool str tuple frozenset bytes None. Mutable:list dict set bytearrayand most user objects. A tuple holding a list is still mutable inside. - Python passes object references by value ("call by sharing"): mutating an argument is visible to the caller, rebinding it is not.
listindex/append O(1),insert(0)/pop(0)/inO(n).dict/setlookup, insert andinare O(1) average (hash tables). Usedequefor queues.- Dicts keep insertion order (guaranteed since 3.7). Keys must be hashable; equal objects must have equal hashes (
1,1.0,Trueare the same key). copy.copy/list.copy()/ slicing make shallow copies (inner objects shared).copy.deepcopycopies recursively and handles cycles.- Mutable default arguments are evaluated once, at
deftime, and shared across calls. UseNoneas the default and create the object inside. - 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). - A decorator is a callable that takes a function and returns a replacement. Decorators with arguments are factories (three levels). Always use
functools.wraps. - Generators (
yield) are lazy iterators that keep their frame between calls. Iterator protocol:__iter__returns the iterator,__next__returns items and raisesStopIteration. withcalls__enter__/__exit__;__exit__always runs, and returningTruefrom it swallows the exception.@contextlib.contextmanagerbuilds one from a generator.@classmethodgetscls(alternative constructors),@staticmethodgets nothing (namespaced helper),@propertymakes a computed/validated attribute.- MRO uses C3 linearization (
Cls.__mro__).super()calls the next class in the MRO, not necessarily the parent — this enables cooperative multiple inheritance. - The GIL lets only one thread run Python bytecode at a time: threads help with I/O, not CPU. Use
multiprocessingfor CPU work andasynciofor many concurrent I/O tasks. 3.13 added an experimental free-threaded build; 3.14 made it officially supported (still optional). - 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 raisesTypeError. - Functions, classes, modules and even types are objects: you can pass them around, store them in dicts and add attributes.
type(int)istype. - Assignment never copies.
b = abinds a second name to the same object. ==calls__eq__(value equality).ischecks identity (same object).x is Noneis the idiomatic None check becauseNoneis a singleton.- CPython caches ints from -5 to 256 and interns many identifier-like strings, so
ismay 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
isand==? - Why does
a is breturn 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 likeappendchange the object in place and returnNone. - 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.heapqgives 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_setfaster thanx 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. *argscollects extra positional arguments into a tuple;kwargscollects extra keyword arguments into a dict**.- At the call site,
*iterableunpacks into positional arguments and**mappinginto keyword arguments. - Positional-only parameters (
/, 3.8+) let you rename them later without breaking callers; many built-ins likelen(obj, /)use them. - Default values are evaluated once, when
defruns, and stored infunc.__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
*argsand**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 namerebinds a module-level name;nonlocal namerebinds 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.xorClassName.x, not barex.
Interview questions
- What is the LEGB rule?
- Difference between
globalandnonlocal? - 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.
@decois syntactic sugar forf = 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)callsretry(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 showwrapper.- Stacked decorators apply bottom-up (the one nearest
defwraps 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; raisesStopIterationwhen done.forcallsiter()thennext()untilStopIteration. - Iterators are single-use; iterables can usually be iterated many times because each
iter()gives a fresh iterator. - A function containing
yieldis a generator function. Calling it returns a generator object; the body runs only onnext()and pauses at eachyield, keeping local state. yield from subdelegates to a sub-iterator (and forwardssend/throw).gen.send(v)resumes the generator and makesyieldevaluate tov.- Comprehensions: list
[...], set{...}, dict{k: v ...}, and generator expressions(...). Generator expressions are lazy and use constant memory. itertoolsgives 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 fromdo? - 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 onreturnorbreak).- Hierarchy:
BaseException→Exception→ most errors.KeyboardInterrupt,SystemExitandGeneratorExitinherit fromBaseExceptiondirectly, soexcept Exceptiondoes not catch them. - Custom exceptions subclass
Exception(often a baseAppErrorfor your package). Add fields for context. raise NewError(...) from errsets__cause__(explicit chain). Raising inside anexceptwithoutfromsets__context__(implicit).from Nonehides 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 byasyncio.TaskGroup), pluserr.add_note().
Interview questions
- What is the purpose of
elseandfinallyin try statements? - Difference between
ExceptionandBaseException? - 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:callsexpr.__enter__()and binds its return value tox. On exit it calls__exit__(exc_type, exc, tb)— withNones if no exception.- If
__exit__returns a truthy value, the exception is suppressed. ReturnFalse/Noneto let it propagate. @contextlib.contextmanagerturns a generator into a context manager: code beforeyieldis setup, after it is teardown. Wrap theyieldintry/finallyso teardown runs on errors.- Common ones: files,
threading.Lock, DB connections/transactions,decimal.localcontext,unittest.mock.patch,tempfile.TemporaryDirectory. contextlibalso hassuppress,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 = valways 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. @classmethodreceives the class: perfect for alternative constructors (from_json) that also work for subclasses.@staticmethodis a plain function grouped in the class.@propertygives getter/setter/deleter logic behind attribute syntax, so you can add validation later without changing callers.- Privacy is by convention:
_namemeans internal.__nametriggers name mangling to_ClassName__nameto avoid clashes in subclasses; it isn't real security.
Interview questions
- Difference between
@classmethodand@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 byprintandstr(). If only__repr__exists,str()falls back to it.__eq__and__hash__go together: defining__eq__sets__hash__toNone(unhashable) unless you define it. Equal objects must have equal hashes; hash only immutable fields.- Return
NotImplemented(notFalse) 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_orderingfills 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 inobject. - 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 oftype(self), not simply the parent. In a diamond,A'ssuper()may callB.- 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+@abstractmethodcreates an abstract base class: you can't instantiate it until all abstract methods are overridden. For structural (duck) typing without inheritance, usetyping.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.
@dataclassgenerates__init__,__repr__and__eq__from type-annotated fields. Options:order=True(comparisons),frozen=True(immutable + hashable). 3.10 addedslots=Trueandkw_only=True.- Mutable defaults must use
field(default_factory=list); a plain= []raisesValueErrorat class creation (dataclasses protect you from the shared-default bug). __post_init__runs after the generated__init__for validation or derived fields.dataclasses.asdict/replacehelp with conversion and copies.typing.NamedTupleis an immutable tuple subclass with named fields: lightweight, hashable, unpackable.Enumgives named, unique, comparable-by-identity constants; members are singletons (Color.RED is Color['RED']). UseIntEnum/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
@dataclassgenerate 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 += 1is several bytecodes, so updates can be lost. UseLock,queue.Queueor 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, runsmainand closes the loop.await xsuspends the current coroutine untilx(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'sasyncio.TaskGroup(async with) is the structured, safer alternative: if one task fails, the rest are cancelled.- Timeouts:
asyncio.wait_for(aw, timeout)orasync with asyncio.timeout(s)(3.11+). Cancellation raisesCancelledErrorinside 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 withawait 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.gathervsTaskGroup?- 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 (gcmodule) 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/WeakValueDictionaryrefer 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, unboundedlru_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 asint | Noneinstead ofOptional[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/Genericfor generics. - 3.12 added PEP 695 syntax:
def first[T](xs: list[T]) -> Tandtype Vector = list[float].typing.Self(3.11) types fluent methods and alternative constructors. - Forward references: quote the name (
'Node') orfrom __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
Protocoland 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
.pyfile; importing it runs its top-level code once and caches it insys.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.modruns a module as a script with correct package imports.- Import search order:
sys.path= script's directory (or cwd),PYTHONPATH, the standard library, thensite-packages. Shadowing a stdlib name (your ownrandom.py) is a common bug. - Virtual environments (
python -m venv .venv) isolate each project's interpreter and packages.pip installputs packages into the active environment'ssite-packages. - Modern projects declare metadata and dependencies in
pyproject.toml, pin with lock files (requirements.txtvia pip-tools, Poetry, or uv), and run tools likeruff(lint/format),mypy/pyright, andpytest.
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 | Yunion 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
typealiases; f-strings formalised (PEP 701: reuse quotes, multi-line, comments); per-interpreter GIL;@typing.override; inlined comprehensions;distutilsremoved. - 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); definedlocals()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/breakinfinallynow warn (PEP 765). - 3.15 (Oct 2026): explicit lazy imports (
lazy import json, PEP 810),frozendictbuilt-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] * 3repeats 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 < cmeansa < b and b < c, soFalse == False in [False]isTrue. - A
returninfinallyoverrides thetry's return and swallows exceptions (3.14 emits aSyntaxWarning). - Functions look up globals when they run, not when defined.
(1)is just1; a one-item tuple needs a comma:(1,).
Interview questions
- What does
[[0] * 3] * 3produce and what's the bug? - Why does
round(2.5)return 2? - What does a function with
returnin bothtryandfinallyreturn?