Pick an option and check it. The explanation shows after each answer. Take as long as you like; nothing is timed and nothing is sent.
20 questions
Question 1 · easy
What does this Python 3.12 program print?
a = [1, 2]
b = a
b += [3]
c = a[:]
c.append(4)
print(a, len(c))
b = a binds a second name to the same list object, and += on a list extends it in place, so a sees the 3. The slice a[:] builds a new list, so appending to c leaves a alone. c started as a copy of [1, 2, 3] and gained one element, so its length is 4.
copy.copy makes a new outer list whose elements are the same inner list objects, so shallow[0][0] = 1 writes into a row that grid shares. copy.deepcopy copies nested objects recursively, so nothing done to deep reaches grid. Use a deep copy (or [row[:] for row in grid] for a list of flat rows) when nested data must be independent.
Question 3 · easy
In Python 3.12, consider:
a = [1, 2, 3]
b = [1, 2, 3]
Which statement about a == b and a is b is correct?
== calls __eq__, which for lists compares the elements one by one; is checks whether both names refer to the very same object. Every list literal creates a new list, so a is b is False. Use is only for identity checks such as x is None; small-integer and string caching is a CPython detail you must not rely on.
Question 4 · hard
What does this Python 3.12 program print?
t = ([1, 2], 3)
try:
t[0] += [4]
status = "ok"
except TypeError:
status = "TypeError"
print(status, t)
t[0] += [4] runs in two steps: list.__iadd__ extends the list in place, then Python stores the result back with t[0] = ..., which fails because a tuple does not support item assignment. The exception is raised after the list was already changed, so both the error and the mutation happen. A tuple fixes which objects it refers to, not the contents of those objects.
Question 5 · easy
Why can the tuple (1, 2) be used as a dictionary key in Python 3.12 while the list [1, 2] cannot?
A dictionary locates a key by its hash, so that hash must never change while the key is stored. Lists are mutable, so list.__hash__ is None and {[1, 2]: 'x'} raises TypeError: unhashable type: 'list'. A tuple hashes its elements, so it works as a key only if everything inside it is hashable: ([1], 2) is not.
Default values are evaluated once, when the def statement runs, so every call that omits tags appends to the same shared list and it keeps growing. tags=list() is evaluated once too, and returning a copy still leaves the shared default accumulating. The None sentinel builds a fresh list per call while still letting a caller pass their own.
Each call to make_counter creates a new count variable and a new inc closure over it, so c1 and c2 keep separate state. nonlocal count tells Python that count += 1 rebinds the enclosing function's variable instead of creating a new local one. c1 is on its third call and c2 on its first.
Question 8 · medium
Calling add(5) in this Python 3.12 program raises UnboundLocalError. What is the cause, and what is the cleanest fix?
total = 0
def add(n):
total += n
return total
add(5)
Scope is decided when the function is compiled: any assignment to a name inside a function makes that name local everywhere in the function, so the read happens before the local has a value. global total makes it work but ties the function to module state, while returning a value is easier to test. nonlocal only refers to an enclosing function's variables, so at module level it is a SyntaxError.
Question 9 · easy
Given this Python 3.12 signature:
def f(a, *args, b=10, **kwargs):
...
What is true about the parameter b?
*args collects all remaining positional arguments into a tuple, so any parameter written after it can only be filled by keyword; these are keyword-only parameters. f(1, 2, 3) gives a=1, args=(2, 3) and leaves b at 10, while f(1, b=5) sets b. **kwargs only receives keyword arguments that match no named parameter.
Question 10 · hard
The author expected this Python 3.12 program to print [0, 10, 20], but it prints [20, 20, 20]. What is the cause, and what is a correct fix?
funcs = []
for i in range(3):
funcs.append(lambda: i * 10)
print([f() for f in funcs])
Closures capture variables, not values: all three lambdas refer to the same i and read it only when called, after the loop has finished with i == 2. A default argument is evaluated when the lambda is created, so it freezes each iteration's value; functools.partial or a small factory function works too. A def inside the loop has exactly the same late-binding behaviour as the lambda.
Question 11 · medium
What is the difference between __new__ and __init__ in a Python 3.12 class?
Cls(...) first calls Cls.__new__(Cls, ...) to build the object, then, if it returned an instance of Cls, calls __init__ on it with the same arguments. Most classes only need __init__. You override __new__ when the object itself must be chosen at creation time, such as subclassing an immutable type like tuple or str, or returning a cached instance.
Question 12 · easy
What does this Python 3.12 program print?
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
def __repr__(self):
return f"Point({self.x}, {self.y})"
def __str__(self):
return f"({self.x}, {self.y})"
p = Point(1, 2)
print(p, [p])
print calls str() on each argument, which uses __str__. A list's string form is built from the repr() of each element, so inside the brackets you see __repr__. Write __repr__ for developers (ideally looking like the constructor call) and __str__ for end users; when only __repr__ is defined, str() falls back to it.
Question 13 · medium
What does this Python 3.12 program print?
class Dog:
tricks = []
legs = 4
def __init__(self, name):
self.name = name
a, b = Dog("Rex"), Dog("Bo")
a.tricks.append("sit")
a.legs = 3
print(b.tricks, b.legs, Dog.legs)
tricks is a class attribute, and a.tricks.append(...) mutates that one shared list, so every Dog sees it. a.legs = 3 is an assignment, which creates an instance attribute on a that shadows the class attribute without touching Dog.legs. Per-object mutable state belongs in __init__, as self.tricks = [].
Question 14 · hard
What does this Python 3.12 program print?
class A:
def hello(self):
return "A"
class B(A):
def hello(self):
return "B" + super().hello()
class C(A):
def hello(self):
return "C" + super().hello()
class D(B, C):
def hello(self):
return "D" + super().hello()
print(D().hello(), [k.__name__ for k in D.__mro__])
Python orders the classes with C3 linearization: a class comes before its parents and the parents keep the order they are listed in, so the MRO is D, B, C, A, object. super() means the next class in the MRO of the instance, not the parent of the current class, so super() inside B reaches C. That is why A runs only once in a diamond and why cooperative super() calls are safe.
Question 15 · medium
In Python 3.12, what happens when the last line of this program runs?
Equal objects must have equal hashes, and an identity hash would break that rule once __eq__ compares values, so Python sets __hash__ = None on such a class. Its instances cannot go into sets or be dictionary keys until you define __hash__ from the same fields __eq__ uses, for example hash(self.uid), and those fields should not change afterwards. @dataclass(frozen=True) generates a matching pair for you.
map, like filter, zip and every generator, returns a one-pass iterator rather than a list. The first list() consumes all its values, so the second finds the iterator exhausted and returns an empty list; list() handles the final StopIteration silently. Convert to a list once if you need the values twice.
Calling a generator function runs none of its body; it only creates a generator object, so created prints first. next(g) runs the body up to the first yield, printing start and handing back 1. The code after that yield waits for another next() call that never comes, so middle is never printed.
Question 18 · easy
Why should the inner wrapper of a decorator be decorated with @functools.wraps(func), as below (Python 3.12)?
Without wraps, the decorated function's __name__ becomes 'wrapper' and its docstring is lost, which confuses logs, tracebacks, help() and frameworks that look functions up by name. functools.wraps copies __name__, __qualname__, __doc__, __module__ and __dict__, and stores the original in __wrapped__. It does not change what the wrapper does when called; caching is functools.lru_cache.
Question 19 · easy
This Python 3.12 program prints calling add and then None instead of 5. What is the fix?
After decoration the name add refers to wrapper, so whatever wrapper returns is what callers receive. This wrapper calls func but discards its result, and a function that ends without return returns None. A general-purpose wrapper should almost always end with return func(*args, **kwargs).
Question 20 · medium
In Python 3.12, what is the main difference between these two lines?
total_a = sum([n * n for n in range(10_000_000)])
total_b = sum(n * n for n in range(10_000_000))
A list comprehension evaluates eagerly and keeps every element, so its memory grows with the input. A generator expression is lazy: it yields each value on demand and keeps only its current state, which suits functions such as sum, max or any that read the values once. The trade-off is that a generator can be iterated only once and supports neither len() nor indexing.
Your answers stay in this browser tab. Nothing is sent or saved.