Python Interview Questions: Live Quiz on Core Language, GIL and Asyncio
Reviewed by Mark Dickie · Last updated
4 questions on this page you can answer and see marked on the spot. Go to the first one
Python is a high-level, interpreted programming language known for readable syntax and a large standard library. Interviews usually test the object model more than syntax: mutable versus immutable objects, how names bind inside functions and closures, iterators and generators, and how the GIL limits threads. Expect at least one question on the standard library or on writing a short program under time pressure. The table below lists the topics that trip up candidates most often, and the numbered list gives hands-on exercises to try before you start the quiz.
Which Python topics do interviewers test most?
| Topic | What interviewers ask | Failure mode to avoid |
|---|---|---|
| Mutable default arguments | Why def f(x=[]) keeps data between calls | Reusing one list across every call without knowing it |
| Late-binding closures | Why lambdas built in a loop all return the same value | Assuming each closure captures the loop value at creation |
is versus == | Identity compared with equality, and small-integer caching | Using is to compare strings or numbers, which passes in tests and fails later |
| GIL and threading | Why threads give little speedup on CPU-bound code | Reaching for threads when multiprocessing is the fix |
| asyncio event loop | What await yields control on, and why time.sleep blocks | Calling a blocking HTTP or sleep call inside a coroutine |
| Generators | How yield keeps memory flat compared with building a list | Wrapping a generator in list() on a large input |
Work through these exercises before the quiz:
- Reproduce the mutable default bug, then fix it with
Noneas the sentinel. - Build a retry decorator that accepts arguments, such as attempt count and delay.
- Write a context manager twice, once with
contextlib.contextmanagerand once as a class with__enter__and__exit__. - Time a CPU-bound function under
threading.Threadand undermultiprocessing.Pool, then explain the gap. - Implement an LRU cache by hand with
collections.OrderedDict, then compare it withfunctools.lru_cache.
Key facts
- Tarmac has 361 Python interview questions on this topic, 10 of them on this page, at difficulty 1–5 of 5.
- Tarmac tracked 3,741 job postings asking for Python in November 2026.
- Roles asking for Python advertise a median base salary of £75,000, across 1,641 job postings as of November 2026.
- Tarmac last reviewed these Python interview questions on 2 November 2026.
At a glance
| Questions | 10 shown · 361 in the bank |
|---|---|
| Difficulty | 1–5 of 5 |
| Formats | True / false, Coding exercise, Find the bug, Flashcard, Ordering, Code output, Multiple choice, Multiple answer, Fill in the blank, Short answer |
| Interactive | 1 run your code against tests, in the app |
What you'll review
- type hints
- slicing
- classmethod staticmethod
- try except else finally
- pytest
Practice questions
Try one before you open the answer. Pick an option and press Check; it's marked on the spot.
In Python, adding type hints to a function causes the interpreter to raise a TypeError at runtime if the caller passes a value of the wrong type.#
Options
Show answer
False — Python type hints are not enforced at runtime. The interpreter treats annotations as metadata only; no TypeError is raised for mismatched types. Static analysis tools like mypy can catch type errors before execution, but the Python runtime itself does not validate them.
Python type hints are purely informational by default. The interpreter does not enforce them at runtime — passing a value of the wrong annotated type will not raise any error unless an external tool (like mypy) or a library (like pydantic) explicitly validates types. This is why Python's type system is described as 'gradual' and optional.
Implement chunk(values, size): split a list into consecutive sublists of length size, with the final chunk shorter if the list doesn't divide evenly. An empty list returns []. You may assume size >= 1.#
Starter code
def chunk(values, size):
# TODO: slice `values` into runs of `size`
return [values]Your solution must pass
- even split
- uneven tail
This one is written and run, not read. Solve it in the app and your code is executed against these tests and the hidden ones.
The function below is intended to return the first element of a list if the list is non-empty, otherwise return None. Running mypy on this file reports exactly one error. Which line does mypy flag?#
from typing import Optional
def first(items: list[int]) -> Optional[int]:
if items:
result: str = items[0]
return int(result)
return NoneShow answer
The bug is on line 5.
Line 5 annotates result as str, but items[0] is an int because items is list[int]. mypy reports exactly one error here: an incompatible assignment of int to a str variable. Line 6 type-checks cleanly because int() accepts a str argument and returns an int, which matches the Optional[int] return type, so it is not flagged. The fix is to change the annotation on line 5 to int (or drop it and let the type be inferred).
What is the difference between @classmethod and @staticmethod?#
Show answer
@classmethod receives the class as its first argument (cls) — useful for alternative constructors and for code that must respect subclassing. @staticmethod receives no implicit first argument; it's just a plain function namespaced on the class, with no access to cls or self.
classmethod binds to the class (cls) so it sees the actual subclass at call time; staticmethod takes neither self nor cls. Reach for classmethod when you need a factory like cls(...), and staticmethod for a utility that just lives on the class.
For a try block that completes WITHOUT raising, order the clauses by when their bodies run.#
Put these in order
Show answer
On the no-exception path the clauses run in this order:
try:bodyelse:body (runs only if no exception)finally:body
The try body runs to completion, then else runs because the block succeeded, then finally always runs last. The except clause is skipped because nothing was raised.
On the no-exception path the try body runs to completion, then else (its whole point — code that should run only when try succeeded), then finally always runs last. except is skipped because nothing was raised.
Assume CPython 3.13 and that the module is run as __main__. What exact line is printed by the following code?#
from __future__ import annotations
from typing import Optional, get_type_hints
class Node:
def __init__(self, val: int, next: Optional[Node] = None) -> None:
self.val = val
self.next = next
hints = get_type_hints(Node.__init__)
print(hints['next'])Show answer
typing.Optional[__main__.Node]
Under from __future__ import annotations, every annotation in Node.__init__ is stored as a string, so the next annotation is the string 'Optional[Node]'. typing.get_type_hints() evaluates those strings in the function's global namespace, where Optional and Node are both defined by the time the call runs (Node is fully defined before the call). The result is the object Optional[Node], which is Union[Node, None]. On CPython 3.13, the repr of this typing object is typing.Optional[__main__.Node], because the class Node defined in the __main__ module is shown with its module-qualified name. The __annotations__ dictionary, by contrast, would still hold the raw string, which is why get_type_hints() is needed to get the evaluated type.
You want to write a generic function first_and_last that accepts any subtype of Sequence[int], including list[int], tuple[int, ...], or a user-defined subclass, and returns a value of that same exact subtype (so passing a tuple[int, ...] should give a tuple[int, ...] result, not just Sequence[int]). Which TypeVar declaration correctly models this constraint?#
Options
Show answer
TypeVar('T', bound=Sequence[int]) is the correct declaration for a generic that accepts any subtype of Sequence[int] while preserving the exact subtype. The bound lets a type checker solve T to the concrete argument type, such as tuple[int, ...] or list[int], instead of collapsing it to one fixed type.
TypeVar('T', bound=Sequence[int]) is correct because a bound constrains T to be a subtype of Sequence[int] while letting the type checker solve T to the specific argument type at each call site. Passing a tuple[int, ...] yields T = tuple[int, ...], so the return annotation T preserves that exact subtype. Option a leaves T unbounded, so any object is accepted and nothing requires a sequence of ints. Option c uses constraints, which force T to resolve to one of the listed types; for a tuple[int, ...] argument the only matching constraint is Sequence[int], so the function returns Sequence[int] and loses the exact subtype the requirement asks to preserve. Option d constrains T to int, str, or float, none of which is a sequence, so every sequence argument would be rejected. The idiomatic tool for "any subtype of X, preserving that subtype" is therefore a bound.
Which of the following statements about Python's typing.Protocol (PEP 544) are correct? Select all that apply.#
Options
Pick every one that applies.
Show answer
The correct statements are: a class satisfies a Protocol through structural compatibility alone — no explicit inheritance needed; a Protocol can inherit from another Protocol to compose required members; and using a plain (non-@runtime_checkable) Protocol in an isinstance() check raises TypeError at runtime. @runtime_checkable checks only attribute presence, not signatures, and Protocol methods lack any runtime enforcement analogous to abc.abstractmethod.
typing.Protocol (PEP 544) enables structural subtyping: a class satisfies a Protocol if it has the required attributes/methods, regardless of inheritance hierarchy. Protocol composition is supported — a Protocol may inherit from one or more other Protocols, merging their required members. Without @runtime_checkable, passing a Protocol to isinstance() raises TypeError at runtime (Python explicitly forbids it). The claim that @runtime_checkable makes isinstance() checks validate full method signatures is wrong because @runtime_checkable only checks for attribute/method presence, not full signature compatibility. The claim that Protocol methods without a default body are enforced at runtime is wrong at the runtime level: unlike abc.abstractmethod, Protocol methods with no default body are not enforced at runtime — Python will happily instantiate a class that omits them; enforcement is purely static (type-checker level).
Complete the pytest test below. Blank _____ is the name of the pytest decorator (the name only, without pytest.mark.) that runs the test once for each (input_val, expected) pair. Blank _____ is the attribute name that appears in the AttributeError message raised by (42).upper(), written as a plain word with no quotes and no regex syntax. The match pattern in the test is r"_____", so it must be that plain word.#
Show answer
Complete the pytest test below. Blank parametrize is the name of the pytest decorator (the name only, without pytest.mark.) that runs the test once for each (input_val, expected) pair. Blank upper is the attribute name that appears in the AttributeError message raised by (42).upper(), written as a plain word with no quotes and no regex syntax. The match pattern in the test is r"**upper**", so it must be that plain word.
import pytest
@pytest.mark.**parametrize**(
"input_val, expected",
[("hello", "HELLO"), ("world", "WORLD"), ("", "")],
)
def test_upper(input_val, expected):
assert input_val.upper() == expected
def test_bad_type():
with pytest.raises(AttributeError, match=r"**upper**"):
(42).upper()
The decorator that runs one test function over several argument sets is @pytest.mark.parametrize, so blank 0 is parametrize. When (42).upper() runs on an integer, CPython raises AttributeError: 'int' object has no attribute 'upper', and the attribute name in that message is upper. Because the prompt requires the plain word with no regex syntax, blank 1 is upper, and pytest.raises(..., match=r"upper") searches successfully within the message, so the test passes.
In Python's typing module (3.10+), what is the primary purpose of ParamSpec, and why is it necessary for correctly typing higher-order functions such as decorators — specifically, what limitation of plain TypeVar does it address?#
Show answer
ParamSpec captures the full parameter specification (names, types, defaults, *args/**kwargs) of a callable so a decorator's return type can reflect the exact signature of the wrapped function. A plain TypeVar can only represent a single type (e.g., the return type); it cannot encode the relationship between the decorator wrapper's parameters and the wrapped function's parameters. Without ParamSpec, the type checker cannot verify that arguments passed to a decorated function match the original function's signature.
ParamSpec (PEP 612, Python 3.10+) captures the full parameter specification (positional + keyword) of a callable so that higher-order functions (like decorators) can preserve the exact call signature of the wrapped function in the type system. TypeVar can only capture the return type or a single type — it cannot represent the relationship between the arguments of the outer wrapper and the inner function. Concatenate[X, P] is used alongside ParamSpec to prepend additional parameters. Without ParamSpec, a generic decorator typed with only TypeVar loses the wrapped function's parameter types, making static analysis blind to argument errors in the decorated call.
Sources
The official documentation these questions are checked against:
Related interview questions
Job market
See python salaries and hiring demand from live job postings.
The other 351 questions
This page shows 10 and marks what you pick. That's as far as a page can go. A free account opens the other 351 and keeps every answer. What you miss comes back until it's right: after a day, then at longer gaps.
Free · the whole bank · 100 answers per 30 days, each marked with written feedback