Python Interview Questions, Intermediate: Defaults, Decorators, Generators (30 questions)
30 intermediate Python interview questions with model answers: data structures, scope and closures, decorators, generators, context managers, classes, dataclasses, exceptions and testing.
Take this exam on Brainbotox, with marking →
Question 1
Q1. Default arguments. What does this program print, and why? Rewrite the function so each call starts with a fresh list.
def add_item(item, items=[]):
items.append(item)
return items
print(add_item(1))
print(add_item(2))
print(add_item(3, []))
Model answer
It prints [1], then [1, 2], then [3].
- A default value is evaluated once, when the
defstatement runs, not at each call. - The one list object is stored on the function (in
add_item.__defaults__) and every call that omitsitemsreceives that same list. - The first call appends 1 to it, the second appends 2 to the same list.
- The third call passes its own list, so the shared one is not used.
Fix: use None as the default and create the list inside.
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return itemsdatetime.now(), which would be frozen at import time. Linters flag it.Revise: Python Intermediate for Confirmed Developers: OOP and Decorators
Question 2
Q2. Decorators.
(a) Write a decorator timed that prints how long the decorated function took. It must work for a function with any arguments, return the function's result, and keep its name and docstring.
(b) What does this line pair really do?
@timed
def load(path): ...
Model answer
(a) The decorator
import functools
import time
def timed(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
try:
return func(*args, **kwargs)
finally:
elapsed = time.perf_counter() - start
print(f"{func.__name__}: {elapsed:.4f}s")
return wrapper*args, **kwargspass any arguments through unchanged.return func(...)gives the caller the real result.finallyprints the time even when the function raises.functools.wrapscopies__name__,__doc__and other metadata onto the wrapper. Without it,load.__name__would be"wrapper".time.perf_counter()is the right clock for measuring durations.
(b) What @timed does: it is shorthand for
def load(path): ...
load = timed(load)A decorator is a function that takes a function and returns a replacement. This works because functions are ordinary objects, and wrapper is a closure that remembers func.
@retry(times=3), needs one more level: a function that returns the decorator.Revise: Python Intermediate for Confirmed Developers: OOP and Decorators
Question 3
Q3. Generators.
(a) What is the difference between these two lines, in memory and in when the work is done?
a = [x * x for x in range(10_000_000)]
b = (x * x for x in range(10_000_000))(b) What does this print, and why?
gen = (x * x for x in range(3))
print(sum(gen))
print(sum(gen))(c) Write a generator function read_lines(path) that yields the non-empty lines of a large file, stripped, without loading the file into memory.
Model answer
(a) List versus generator
ais a list comprehension: it computes all ten million squares now and stores them all, hundreds of megabytes.bis a generator expression: it computes nothing yet. It produces one value each time it is asked, and uses a small constant amount of memory. This is lazy evaluation.
The list can be indexed, measured with len() and read many times. The generator can only be read forward, once.
(b) It prints 5 then 0. The first sum consumes 0, 1 and 4. The generator is then exhausted, so the second sum receives nothing and returns 0. No error is raised, which makes this bug easy to miss.
(c) Generator function
def read_lines(path):
with open(path, encoding="utf-8") as f:
for line in f:
line = line.strip()
if line:
yield lineyieldhands one value to the caller and pauses the function, keeping its local variables. The next request resumes it on the following line.- Iterating over the file object reads one line at a time.
- The
withblock closes the file when the generator finishes or is closed.
sum(len(l) for l in read_lines(p)), and each stage holds one item at a time.Revise: Python Intermediate for Confirmed Developers: OOP and Decorators
Question 4
Q4. Choosing a collection. Compare list, tuple, set and dict. Why is the second test below much faster than the first when there are a million items?
names_list = [...] # 1,000,000 strings
names_set = set(names_list)
"zoe" in names_list
"zoe" in names_set
Model answer
list: ordered, mutable sequence. Good for items you iterate over or index by position.tuple: ordered and immutable. Good for fixed records, and usable as a dict key if its items are hashable.set: unordered collection of unique, hashable items. Good for membership tests and removing duplicates.dict: maps hashable keys to values, keeps insertion order.
x in list compares x with each item in turn: O(n), up to a million comparisons.
x in set hashes x and looks in one place of a hash table: O(1) on average, whatever the size.
Same for dict keys. A classic fix for a slow loop is turning the list you search in into a set once, before the loop:
blocked = set(blocked_list)
allowed = [u for u in users if u.id not in blocked]The price: a set uses more memory, has no order and cannot hold unhashable items such as lists.
Question 5
Q5. is and ==. What is the difference between is and ==? What does this print? When is is the right operator?
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a == b, a is b, a is c)
Model answer
It prints True False True.
==tests equality of values. It calls__eq__. Two different lists with the same contents are equal.istests identity: are these the very same object in memory? It comparesid(a)andid(b).aandbare two objects.cis another name for the objectarefers to.
Use is only for singletons:
if value is None: ...
if flag is True: ... # rarely needed
if x is not None: ...is None is preferred to == None: it is faster and cannot be fooled by a class that overrides __eq__.
Never use is to compare numbers or strings. It sometimes appears to work, because CPython reuses small integers and some strings, but that is an implementation detail:
x = 1000
y = 1000
x is y # may be True or FalseRecent Python versions emit a SyntaxWarning for is with a literal.
Question 6
Q6. Shallow and deep copies. What does this print, and why? How do you make a fully independent copy?
a = [[1, 2], [3, 4]]
b = a.copy()
b[0].append(99)
b.append([5])
print(a)
Model answer
It prints [[1, 2, 99], [3, 4]].
a.copy() makes a shallow copy: a new outer list, whose items are references to the same inner lists.
b[0].append(99)changes an inner list that bothaandbrefer to, soasees it.b.append([5])changes only the outer list ofb, soadoes not see it.
Other shallow copies: a[:], list(a), dict(d), copy.copy(x).
For a fully independent copy, use a deep copy, which copies nested objects recursively:
import copy
b = copy.deepcopy(a)Remember that plain assignment copies nothing at all: b = a makes b another name for the same list.
deepcopy is slow on large structures. Often a better design is to avoid mutating shared data: build new lists instead of changing existing ones, or use immutable types such as tuples.
Question 7
Q7. A grid that is not a grid. What does this print? Explain, and write the correct way to create a 3 by 3 grid of zeros.
grid = [[0] * 3] * 3
grid[0][0] = 1
print(grid)
Model answer
It prints [[1, 0, 0], [1, 0, 0], [1, 0, 0]].
Multiplying a list repeats its references, it does not copy the items.
[0] * 3is fine: it repeats the integer 0, which is immutable.[row] * 3creates an outer list containing the same row object three times. Changinggrid[0][0]changes that one row, which shows up in all three positions.
You can check with grid[0] is grid[1], which is True.
Correct version: a list comprehension evaluates [0] * 3 once per iteration, so each row is a new list.
grid = [[0] * 3 for _ in range(3)]
grid[0][0] = 1
print(grid) # [[1, 0, 0], [0, 0, 0], [0, 0, 0]]The same trap exists with dict.fromkeys(keys, []): every key gets the same list. Use {k: [] for k in keys}.
Question 8
Q8. Function parameters. Explain *args and **kwargs. In the signature below, how may each parameter be passed?
def connect(host, /, port=5432, *, timeout=10, **options):
...
Model answer
*argscollects extra positional arguments into a tuple.**kwargscollects extra keyword arguments into a dict.
The same stars unpack at the call site: f(*items, **settings).
In the signature:
hostis before/, so it is positional-only.connect(host="db")is an error. This lets the author rename the parameter later without breaking callers.portis between/and*: it can be passed by position or by name.timeoutis after*, so it is keyword-only. It must be writtentimeout=30. This keeps calls readable and avoids mixing up arguments.**optionsreceives any other keyword arguments.
connect("db") # ok
connect("db", 5433, timeout=30, ssl=True) # ok, options = {"ssl": True}
connect("db", 5433, 30) # TypeError: too many positionalOrder in a definition: positional-only, /, normal, *args or *, keyword-only, **kwargs.
Question 9
Q9. Scope. What happens when this runs, and why? Give two ways to fix it.
count = 10
def show():
print(count)
count = 5
show()
Model answer
It raises UnboundLocalError on the print line. It does not print 10.
Python decides the scope of each name when the function is compiled, not line by line. Because count is assigned somewhere in show, it is a local variable for the whole function. The print then reads the local before it has a value.
Name lookup follows the LEGB order: Local, Enclosing function, Global, Built-in. Reading a global needs nothing special. Assigning creates a local unless you say otherwise.
Fix 1, if the function should change the global:
def show():
global count
print(count)
count = 5Fix 2, usually better: do not modify globals. Pass the value in and return the new one.
def show(count):
print(count)
return 5
count = show(count)For a variable of an enclosing function (a closure), the keyword is nonlocal:
def counter():
n = 0
def inc():
nonlocal n
n += 1
return n
return inc
Question 10
Q10. Closures in a loop. What does this print? Fix it so it prints [0, 1, 2].
funcs = [lambda: i for i in range(3)]
print([f() for f in funcs])
Model answer
It prints [2, 2, 2].
A closure captures the variable, not its value at the time the function was created. All three lambdas refer to the same i. They are called after the loop has finished, when i is 2. This is called late binding.
Fix 1: bind the current value as a default argument. Defaults are evaluated when the function is defined.
funcs = [lambda i=i: i for i in range(3)]Fix 2: functools.partial, which stores the argument immediately.
from functools import partial
def ident(i):
return i
funcs = [partial(ident, i) for i in range(3)]Fix 3: a factory function, which gives each closure its own variable.
def make(i):
return lambda: i
funcs = [make(i) for i in range(3)]The same bug appears when creating callbacks in a loop, for example button handlers in a GUI or tasks scheduled for later.
Question 11
Q11. Comprehensions. Using comprehensions, write: (a) a dict that swaps keys and values of d = {"a": 1, "b": 2}, (b) the set of distinct word lengths in a list of words, (c) a flat list from [[1, 2], [3], [4, 5]]. When should you not use a comprehension?
Model answer
# (a) dict comprehension
inverted = {v: k for k, v in d.items()} # {1: "a", 2: "b"}
# (b) set comprehension
lengths = {len(w) for w in words}
# (c) nested: read the for clauses left to right
flat = [x for row in rows for x in row] # [1, 2, 3, 4, 5]With a condition:
evens = [n * n for n in numbers if n % 2 == 0]A comprehension builds a new collection from an iterable in one expression. It is faster than a loop with append, and states the intent clearly.
Do not use one when:
- it is only for side effects:
[print(x) for x in items]builds a useless list. Write aforloop. - it needs more than two
forclauses or complex conditions: a loop is easier to read and debug. - the result is huge and only iterated once: use a generator expression, with round brackets, which produces items one at a time.
total = sum(n * n for n in numbers) # no list in memoryNote on (a): if two keys share a value, the later one wins.
Question 12
Q12. The iterator protocol. What is the difference between an iterable and an iterator? Write a class Countdown(3) that can be used in a for loop and yields 3, 2, 1.
Model answer
- An iterable is anything you can loop over. It has an
__iter__()method that returns an iterator. Lists, strings, dicts and files are iterables. - An iterator produces the values one at a time. It has
__next__(), which returns the next value or raisesStopIterationwhen there are no more, and an__iter__()that returns itself.
A for loop calls iter(obj) once, then next() repeatedly until StopIteration.
class Countdown:
def __init__(self, start):
self.start = start
def __iter__(self):
n = self.start
while n > 0:
yield n
n -= 1
for n in Countdown(3):
print(n) # 3, 2, 1Writing __iter__ as a generator is the simplest way: Python builds the iterator for you, and each loop gets a fresh one, so the object can be iterated several times.
The manual version, for comparison:
class CountdownIter:
def __init__(self, start):
self.n = start
def __iter__(self):
return self
def __next__(self):
if self.n <= 0:
raise StopIteration
self.n -= 1
return self.n + 1This one is its own iterator, so it is exhausted after one pass.
Question 13
Q13. Context managers. What does the with statement guarantee? Write a context manager timer() that prints how long the block took, in two ways.
Model answer
with guarantees that clean-up code runs when the block is left, whether it ends normally, with a return, or with an exception. It replaces try/finally for resources: files, locks, connections, transactions.
As a class, with the two special methods:
import time
class Timer:
def __enter__(self):
self.start = time.perf_counter()
return self # bound by "as"
def __exit__(self, exc_type, exc, tb):
print(f"{time.perf_counter() - self.start:.3f}s")
return False # do not swallow exceptions
with Timer():
work()As a generator, usually shorter:
from contextlib import contextmanager
@contextmanager
def timer():
start = time.perf_counter()
try:
yield # the block runs here
finally:
print(f"{time.perf_counter() - start:.3f}s")
with timer():
work()The code before yield is the set-up, the code after is the clean-up. The try/finally is needed so the clean-up runs even if the block raises.
__exit__ receives the exception, if any. Returning True suppresses it, which is rarely what you want.
Question 14
Q14. try, except, else, finally. What does this print, and in what order? What is the else clause of a try for?
def f():
try:
return "try"
finally:
print("finally")
print(f())
Model answer
It prints finally, then try.
The return prepares the value, but before the function actually returns, the finally block runs. finally always runs: after a normal end, a return, a break, or an exception.
Trap: a return inside finally replaces the earlier return value and silently discards any exception in progress. Do not write one.
The four clauses:
try:
data = load()
except FileNotFoundError as e:
print("missing:", e) # runs if that exception was raised
else:
process(data) # runs only if NO exception was raised
finally:
close() # always runselse holds the code that should run only when the try succeeded, without being protected by the except. If process(data) were inside the try, a FileNotFoundError raised by process would be caught by mistake and reported as a missing file.
Good habits: catch specific exceptions, never a bare except: (it also catches KeyboardInterrupt and SystemExit), and keep the try block as small as possible.
Question 15
Q15. Raising and wrapping. Define a custom exception for a payment module and show how to raise it from a lower-level error without losing the original. What does EAFP mean?
Model answer
class PaymentError(Exception):
"""Base class for errors in this module."""
class CardDeclined(PaymentError):
def __init__(self, reason):
super().__init__(f"card declined: {reason}")
self.reason = reason
def charge(card, amount):
try:
gateway.pay(card, amount)
except ConnectionError as e:
raise PaymentError("gateway unreachable") from e- Inherit from
Exception, notBaseException. - A base class per package lets callers catch everything from it with one
except PaymentError. raise X from ekeeps the original exception as__cause__. The traceback shows both, with "The above exception was the direct cause of the following exception". Withoutfrom, the chain is still shown but labelled as happening "during handling", as if it were an accident. Usefrom Noneto hide the cause on purpose.
EAFP: easier to ask forgiveness than permission. Try the operation and handle the failure, instead of checking first (LBYL, look before you leap).
# EAFP
try:
value = config["port"]
except KeyError:
value = 8080
# LBYL
if "port" in config:
value = config["port"]EAFP is the usual Python style. It avoids a gap between the check and the use, which matters with files and concurrency.
Question 16
Q16. Class and instance attributes. What does this print? Explain and fix the class.
class Dog:
tricks = []
def add(self, trick):
self.tricks.append(trick)
a = Dog()
b = Dog()
a.add("sit")
print(b.tricks)
Model answer
It prints ['sit'], although nothing was added to b.
tricks = [] in the class body is a class attribute: one list, stored on the class, shared by every instance. self.tricks finds no attribute on the instance, so it falls back to the class and returns that shared list. append then mutates it for everyone.
Fix: create the list per instance in __init__.
class Dog:
def __init__(self):
self.tricks = []
def add(self, trick):
self.tricks.append(trick)The difference between mutating and assigning matters:
class Counter:
count = 0
c = Counter()
c.count += 1 # creates an INSTANCE attribute on c
print(Counter.count) # still 0c.count += 1 reads the class value, adds 1, and assigns to the instance, which creates a new attribute there.
Class attributes are right for constants and for data that is meant to be shared: a default value, a registry, a count of instances updated through Counter.count += 1.
Question 17
Q17. Kinds of method. Explain the difference between an instance method, a @classmethod and a @staticmethod. Give a typical use of a class method.
Model answer
- Instance method: receives the instance as
self. It can read and change that object's state. @classmethod: receives the class ascls, not an instance. It can be called on the class or on an instance.@staticmethod: receives nothing automatically. It is an ordinary function placed in the class's namespace because it belongs with it logically.
The typical use of a class method is an alternative constructor:
from datetime import date
class User:
def __init__(self, name, born):
self.name = name
self.born = born
@classmethod
def from_csv(cls, line):
name, year = line.split(",")
return cls(name, int(year)) # cls, not User
@staticmethod
def is_valid_name(name):
return name.isalpha()
def age(self):
return date.today().year - self.born
u = User.from_csv("Ada,1990")Using cls(...) instead of User(...) matters with inheritance: Admin.from_csv(...) returns an Admin.
A static method that uses neither the class nor the instance can often simply be a module-level function. Keep it in the class only when it is clearly part of the class's interface.
Question 18
Q18. Properties. A class has a public attribute temperature. Later you need to reject values below absolute zero, without changing the code of the callers. Show how.
Model answer
class Sensor:
def __init__(self, temperature):
self.temperature = temperature # goes through the setter
@property
def temperature(self):
return self._temperature
@temperature.setter
def temperature(self, value):
if value < -273.15:
raise ValueError("below absolute zero")
self._temperature = value
@property
def fahrenheit(self): # computed, read-only
return self._temperature * 9 / 5 + 32
s = Sensor(20)
s.temperature = 25 # calls the setter
print(s.temperature) # calls the getter
s.temperature = -300 # ValueErrorA @property makes a method look like an attribute. Callers keep writing s.temperature, with no change to their code, while the class now runs logic on each access.
This is why Python code does not start with getters and setters as in Java: begin with a plain attribute, and turn it into a property only when you need validation, a computed value or a read-only field.
- A property without a setter is read-only: assigning raises
AttributeError. - The real value lives in
_temperature. The leading underscore is a convention meaning "internal", not an access restriction. - Keep properties cheap. Something slow or with side effects should be a method, so the call is visible.
Question 19
Q19. Special methods. What is the difference between __repr__ and __str__? What happens to hashing when you define __eq__ on a class?
Model answer
__repr__is for developers: an unambiguous description, ideally the code that would recreate the object. It is used by the interactive prompt, byrepr(), in debuggers and inside containers.__str__is for end users: a readable form, used byprint()andstr().
If __str__ is missing, Python falls back to __repr__. So always define __repr__ first.
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
def __repr__(self):
return f"Point(x={self.x}, y={self.y})"
def __eq__(self, other):
if not isinstance(other, Point):
return NotImplemented
return (self.x, self.y) == (other.x, other.y)
def __hash__(self):
return hash((self.x, self.y))Equality and hashing:
- By default objects compare by identity and are hashable.
- If you define
__eq__and not__hash__, Python sets__hash__toNone: instances become unhashable and cannot be put in a set or used as dict keys. - The rule to respect: objects that are equal must have the same hash. So hash the same fields you compare, and only if they do not change.
Return NotImplemented (not False) for an unknown type, so Python can try the other operand's method.
Question 20
Q20. Method resolution order. What does this print, and why does A appear only once?
class A:
def hi(self): print("A")
class B(A):
def hi(self): print("B"); super().hi()
class C(A):
def hi(self): print("C"); super().hi()
class D(B, C):
def hi(self): print("D"); super().hi()
D().hi()
Model answer
It prints D, B, C, A.
With multiple inheritance, Python computes a single linear order of classes for each class, the method resolution order (MRO), using the C3 algorithm. It keeps each class before its parents and respects the order in which the bases are listed.
print(D.__mro__)
# D, B, C, A, objectThe key point: super() does not mean "my parent class". It means the next class in the MRO of the object's actual type.
- In
D.hi, the next class isB. - In
B.hi, called on aDinstance, the next class isC, notA, even thoughBinherits only fromA. - In
C.hi, the next isA.
So each class runs exactly once, and the shared base A runs last. If B had called A.hi(self) directly, C would have been skipped.
This is cooperative inheritance: it works when every class in the chain calls super() and the methods have compatible signatures. It is what makes mixins possible.
Question 21
Q21. Abstract base classes and protocols. What is duck typing? Compare an abstract base class (abc.ABC) with a typing.Protocol for defining an interface.
Model answer
Duck typing: a function does not check the type of its argument. It just uses the methods it needs. Any object that has them works: "if it walks like a duck and quacks like a duck".
Abstract base class: nominal typing. A class must inherit from it explicitly.
from abc import ABC, abstractmethod
class Storage(ABC):
@abstractmethod
def save(self, key: str, data: bytes) -> None: ...
class DiskStorage(Storage):
def save(self, key, data): ...
Storage() # TypeError: cannot instantiate abstract classA subclass that forgets an abstract method cannot be instantiated: the error appears at run time, when the object is created. An ABC can also carry shared code.
Protocol: structural typing. A class matches if it has the right methods, with no inheritance. It is duck typing that a type checker can verify.
from typing import Protocol
class Saver(Protocol):
def save(self, key: str, data: bytes) -> None: ...
class S3Storage: # no base class
def save(self, key, data): ...
def backup(target: Saver): ...
backup(S3Storage()) # accepted by mypyChoose a Protocol when you want to accept types you do not control, or to keep modules decoupled. Choose an ABC when you own the hierarchy and want shared behaviour and a run-time check.
Question 22
Q22. Dataclasses. What does @dataclass generate? What is wrong with tags: list = [] in a dataclass, and what do frozen=True and slots=True do?
Model answer
from dataclasses import dataclass, field
@dataclass
class Order:
id: int
customer: str
total: float = 0.0
tags: list[str] = field(default_factory=list)From the annotated fields, the decorator generates __init__, __repr__ and __eq__. You get Order(1, "Ada"), a readable repr, and comparison by field values, without writing them.
Mutable defaults: tags: list = [] would share one list between all instances, the same trap as a mutable default argument. The dataclass decorator refuses it with a ValueError. Use field(default_factory=list), which calls list() for each new instance.
Options:
frozen=True: instances are immutable. Assigning to a field raisesFrozenInstanceError. With the defaulteq=Trueit also makes them hashable, so they can be dict keys or set members.slots=True(Python 3.10+): generates__slots__. Less memory per instance, faster attribute access, and no accidental new attributes.order=True: adds<,>and so on, comparing fields in order.kw_only=True: all fields must be passed by keyword.
Use __post_init__ for validation or derived fields. The type annotations are not checked at run time.
Question 23
Q23. Type hints. Does this raise an error when it runs? What are type hints for, and how are they checked?
def double(n: int) -> int:
return n * 2
print(double("ab"))
Model answer
No error. It prints abab.
Type hints are not enforced at run time. Python stores them in __annotations__ and otherwise ignores them. The string is multiplied by 2 as usual.
They are checked by external tools before the program runs:
- static type checkers:
mypy,pyright; - editors, which use them for completion and for underlining mistakes.
A checker reports the call: argument 1 has incompatible type str, expected int.
What hints give you: bugs found before running, safer refactoring, better tooling, and documentation that cannot drift from the code.
Common forms:
def find(users: list[str], name: str) -> int | None: ...
def load(path: str, retries: int = 3) -> dict[str, int]: ...
from collections.abc import Callable, Iterable
def apply(f: Callable[[int], str], xs: Iterable[int]) -> list[str]: ...int | None (Python 3.10+) is the same as Optional[int].
When you do need run-time validation, for example of JSON from outside, use a library built for it, such as pydantic, which reads the annotations and checks the data.
Question 24
Q24. Imports. What happens when Python executes import mymodule for the first time, and for the second time? What is if __name__ == "__main__": for?
Model answer
First import:
- Python looks for the module in
sys.modules, a cache of modules already loaded. It is not there. - It searches the directories of
sys.pathfor the file. - It creates a module object and runs the whole file from top to bottom. Every top-level statement executes: definitions, assignments, and any calls.
- It stores the module in
sys.modulesand binds the name in the importing module.
Later imports, from anywhere in the program: the module is found in sys.modules and returned at once. The file is not run again. So a module is effectively a singleton, and its top-level variables are shared.
The __main__ guard: every module has a __name__. It is the module's name when imported, and "__main__" when the file is run directly.
def main():
...
if __name__ == "__main__":
main()The guarded code runs with python mymodule.py, but not on import mymodule. Without it, importing the file for one function would also start the program. It is also required for multiprocessing on Windows and macOS, where child processes import the main module.
Consequences: keep work out of the top level, and beware of circular imports: if a imports b while b imports a, one of them sees a half-initialised module.
Question 25
Q25. Environments and dependencies. What is a virtual environment and why use one? What is the difference between listing requests>=2.0 and pinning exact versions?
Model answer
A virtual environment is an isolated directory with its own Python interpreter links and its own site-packages. Packages installed there are visible only to that project.
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install requestsWhy: two projects can need different versions of the same library, and installing into the system Python can break tools the operating system depends on. One environment per project avoids both.
Declaring dependencies: two different needs.
- Ranges (
requests>=2.0) say what your code is compatible with. This is what a library declares, inpyproject.toml, so it can be combined with other packages. - Pinned versions (
requests==2.32.3, including every indirect dependency) say exactly what was tested. This is what an application deploys, so that a build today and a build in six months install the same code.
Without pinning, a new release of any dependency can break production with no change on your side.
Tools produce the pinned list (a lock file) from the ranges: pip-tools, poetry, uv. Commit the lock file, and do not commit the .venv directory.
Question 26
Q26. Building strings. Why can the first version be slow for a large list, and what is the idiomatic alternative? Show three features of f-strings.
result = ""
for word in words:
result += word + ", "
Model answer
Strings are immutable. Each += may create a new string and copy everything accumulated so far, so the total work can grow with the square of the length. CPython sometimes optimises this in place, but that is not guaranteed and does not exist in other implementations.
The idiomatic form:
result = ", ".join(words)join computes the final size once, allocates once and copies each piece once. It also puts the separator between items, with none left over at the end. The items must be strings: ", ".join(str(n) for n in numbers).
When building in several steps, collect pieces in a list and join at the end, or use io.StringIO.
f-strings (Python 3.6+) evaluate expressions inside the string:
name, price, n = "tea", 3.14159, 42
f"{name.upper()} costs {price:.2f}" # 'TEA costs 3.14' expression + format
f"{n:>6}|{n:<6}|{n:06}" # ' 42|42 |000042' alignment, padding
f"{n=}" # 'n=42' name and value, for debugging
f"{1_000_000:,}" # '1,000,000'They are faster and clearer than % formatting or str.format.
One exception: do not use f-strings to build SQL with user input. Use query parameters, to avoid SQL injection.
Question 27
Q27. Sorting. What is the difference between list.sort() and sorted()? Sort a list of dicts people by age from oldest to youngest, and by name alphabetically for people of the same age.
Model answer
list.sort()sorts the list in place and returnsNone. It exists only on lists.sorted(iterable)returns a new list and leaves the original alone. It accepts any iterable.
Classic bug: items = items.sort() sets items to None.
Both take key, a function called once per item to produce the value to compare, and reverse.
ordered = sorted(people, key=lambda p: (-p["age"], p["name"]))The key is a tuple. Tuples compare element by element, so the age decides first and the name breaks ties. Negating the age gives descending order for that field only.
When a field cannot be negated, such as a string, use the fact that Python's sort is stable: items with equal keys keep their existing order. Sort by the secondary key first, then by the primary key.
people.sort(key=lambda p: p["name"]) # secondary
people.sort(key=lambda p: p["age"], reverse=True) # primaryoperator.itemgetter("age") and operator.attrgetter("age") are faster alternatives to a lambda.
The algorithm (Timsort) is O(n log n), and very fast on data that is already partly sorted. For only the few largest items, heapq.nlargest(3, people, key=...) avoids sorting everything.
Question 28
Q28. The collections module. For each task, name the right tool from collections and show one line of use: (a) count the words in a list, (b) group words by first letter, (c) a queue that is fast at both ends, (d) a lightweight record with named fields.
Model answer
from collections import Counter, defaultdict, deque, namedtuple
# (a) Counter: counts hashable items
counts = Counter(words)
counts.most_common(3) # the 3 most frequent, with their counts
# (b) defaultdict: creates a missing value on first access
groups = defaultdict(list)
for w in words:
groups[w[0]].append(w) # no "if key not in" needed
# (c) deque: double-ended queue
q = deque(maxlen=100)
q.append(x) # add on the right
q.popleft() # remove on the left, O(1)
# (d) namedtuple: tuple with field names
Point = namedtuple("Point", ["x", "y"])
p = Point(1, 2)
p.x, p[0] # both workCounteris a dict subclass. Missing keys count as 0, and counters can be added and subtracted.defaultdictcalls its factory (list,int,set) for a missing key. Note that merely reading a missing key creates it.deque:list.pop(0)is O(n) because every remaining item shifts, whiledeque.popleft()is O(1). Withmaxlenit keeps only the last N items, which is handy for a sliding window or recent history.namedtupleis immutable and as light as a tuple. For new code,typing.NamedTupleor a@dataclassgives the same with type hints.
Question 29
Q29. Memoisation. This function is extremely slow for fib(35). Why? Make it fast with one line, and state the conditions for that to work.
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
Model answer
Each call makes two more calls, and the same values are recomputed again and again: fib(33) is computed twice, fib(32) three times, and so on. The number of calls grows exponentially, about 30 million for fib(35).
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)lru_cache stores each result in a dict keyed by the arguments. A repeated call returns the stored value at once. Each fib(k) is now computed once, so the work is linear. This technique is called memoisation. functools.cache (Python 3.9+) is the same as lru_cache(maxsize=None).
Conditions:
- The arguments must be hashable: no lists or dicts. Pass tuples.
- The function must be pure: the same arguments always give the same result, with no side effects. Caching a function that reads the clock, a file or a database returns stale data.
- Mind the memory: with
maxsize=Nonethe cache grows without limit. Give a size (maxsize=1024) to keep only the most recently used results.
Useful extras: fib.cache_info() shows hits and misses, fib.cache_clear() empties it.
For Fibonacci itself, a simple loop is better still: no recursion limit and no cache.
Question 30
Q30. Testing with pytest. Write tests for def divide(a, b): return a / b covering several inputs and the division by zero. Explain what a fixture is and how you replace a dependency in a test.
Model answer
import pytest
from calc import divide
@pytest.mark.parametrize("a, b, expected", [
(6, 3, 2),
(1, 4, 0.25),
(-9, 3, -3),
])
def test_divide(a, b, expected):
assert divide(a, b) == expected
def test_divide_by_zero():
with pytest.raises(ZeroDivisionError):
divide(1, 0)- pytest collects functions named
test_*and uses plainassert. On failure it shows the values of both sides. parametrizeruns the same test once per row, and reports each case separately.pytest.raisespasses only if the block raises that exception.- For floats, compare with
pytest.approx(0.3).
A fixture is a function that prepares something a test needs, and cleans it up afterwards. A test receives it by naming it as a parameter.
@pytest.fixture
def db(tmp_path):
conn = connect(tmp_path / "test.sqlite")
yield conn # the test runs here
conn.close() # clean-up
def test_insert(db):
db.insert("ada")
assert db.count() == 1Replacing a dependency: the built-in monkeypatch fixture swaps an attribute for the duration of one test and restores it afterwards.
def test_weather(monkeypatch):
monkeypatch.setattr("app.weather.fetch_temp", lambda city: 21)
assert app.weather.report("Paris") == "Paris: 21 C"This keeps tests fast and independent of the network. unittest.mock.patch does the same and can also record how the fake was called.