Lesson 14 of 32Question banks
Python Interview Questions
Answer the Python questions interviewers ask most, from mutability and the GIL to decorators and the MRO.
Python roles almost always include a few minutes of "language questions" before or after the coding problem. They are quick to ask, quick to fail, and they reveal whether you have used Python for real or only followed tutorials. This lesson collects the ones that come up most, each with a crisp answer you can say in under a minute.
Read the question, answer it out loud, then open the model answer and compare.
Objects, names, and mutability
"What is the difference between mutable and immutable types?" A mutable object can be changed in place after it is created (list, dict, set, most class instances). An immutable one cannot (int, float, str, tuple, frozenset, bytes). "Changing" an immutable value really creates a new object and rebinds the name to it.
Python variables are names that point to objects, not boxes that hold values. Two names can point to the same object, and that is where mutability starts to matter.
a points to a new list object.
Model answer: is vs ==
== compares values by calling __eq__. is compares identity: whether both names point to the exact same object (same id()). Use is only for singletons like None, True, and False (if x is None). Do not rely on is for numbers or strings: CPython caches small ints (-5 to 256) and some strings, so is may appear to work by accident.
What does this print?
a = [1, 2, 3] b = a c = [1, 2, 3] print(a == c, a is c, a is b)
Model answer: list vs tuple
Both are ordered sequences. A list is mutable and meant for a variable number of items of the same kind. A tuple is immutable and often used for a fixed record of positions, like (lat, lng). Because tuples are immutable (if their items are hashable), they can be dict keys and set members; lists cannot. Tuples are also slightly smaller in memory and faster to create.
def add(item, bucket=[]):
bucket.append(item)
return bucket
add("a")
print(add("b"))Model answer: shallow vs deep copy
A shallow copy (list(x), x.copy(), x[:], copy.copy(x)) creates a new outer container but keeps references to the same inner objects. A deep copy (copy.deepcopy(x)) recursively copies everything, so nested lists and dicts are independent. Shallow is cheaper and enough for flat data; deep is needed when you will mutate nested objects.
Press Run (⌘ Enter) to see what happens.Dicts and hashing
"How does a dict work, and why must keys be hashable?" A dict is a hash table. Python calls hash(key) to get an integer, uses it to pick a slot in an internal array, and stores the key and value there. Lookup repeats the hash and checks the slot, so get, set, and in are O(1) on average. Collisions (two keys landing on the same slot) are resolved by probing other slots, and the table resizes when it gets about two-thirds full.
A key must be hashable: its hash must never change while it is in the dict, and equal objects must have equal hashes. That is why mutable lists cannot be keys. Since Python 3.7, dicts also keep insertion order as a language guarantee.
None picked yet
Functions: args, decorators, generators
Model answer: *args and **kwargs
*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. The names are convention; the * and ** do the work. The same symbols unpack at the call site: f(*items, **options). They are common in wrappers and decorators that forward whatever they receive.
"What is a decorator?" A function that takes a function and returns a new function, usually wrapping the original with extra behaviour (timing, caching, auth checks). @timer above a def is shorthand for f = timer(f). Use functools.wraps so the wrapper keeps the original's name and docstring.
Press Run (⌘ Enter) to see what happens."What is a generator, and why use one?" A function containing yield. Calling it returns a generator object that produces values lazily, one per next(), pausing between them and keeping its local state. It uses O(1) memory however many values it yields, so it suits large files, streams, and infinite sequences. Generator expressions (x * x for x in nums) are the one-line version.
What does this print?
def count_up(n):
for i in range(n):
print("yield", i)
yield i
g = count_up(3)
print(next(g))
print(next(g))Model answer: comprehension scoping
In Python 3, list, set, and dict comprehensions and generator expressions have their own scope, so the loop variable does not leak: after [x for x in range(3)], x is not defined outside (unless it already was, in which case it is unchanged). In Python 2 list comprehensions did leak. A plain for loop still leaks its variable in Python 3.
Concurrency and the GIL
"What is the GIL?" The Global Interpreter Lock is a mutex in CPython that lets only one thread execute Python bytecode at a time. It makes reference counting and memory management simple and fast, but it means threads do not speed up CPU-bound Python code.
How to choose:
| Workload | Tool | Why |
|---|---|---|
| I/O-bound, many connections (HTTP, DB) | asyncio | One thread, thousands of waiting tasks, very cheap |
| I/O-bound with blocking libraries | threading / ThreadPoolExecutor | The GIL is released while waiting on I/O |
| CPU-bound (number crunching, parsing) | multiprocessing / ProcessPoolExecutor | Separate processes, each with its own GIL |
Since Python 3.13 there is an optional free-threaded build (python3.13t) with no GIL, and it became officially supported in 3.14. It is not yet the default, and many C extensions still assume the GIL, so a strong answer mentions it as "coming" rather than "solved".
Classes
Model answer: __init__ vs __new__
__new__ creates the instance (it is a static method that receives the class and returns a new object). __init__ initialises the already-created instance and returns None. You almost never override __new__; the main uses are subclassing immutable types like int or str, or implementing singletons and caching.
Model answer: @staticmethod vs @classmethod
A normal method receives the instance (self). A @classmethod receives the class (cls), so it can build instances and works correctly for subclasses; it is the standard way to write alternative constructors like User.from_dict(data). A @staticmethod receives neither; it is a plain function namespaced inside the class because it belongs there logically.
"What is the MRO?" The method resolution order is the order Python searches classes for an attribute when there is inheritance, especially multiple inheritance. Python computes it with the C3 linearization algorithm: a child comes before its parents, and parents keep the order in which they were listed. You can see it with Class.__mro__. super() follows the MRO, not just "the parent", which is what makes cooperative multiple inheritance work.
What does this print?
class A: def hi(self): return "A" class B(A): def hi(self): return "B" class C(A): def hi(self): return "C" class D(B, C): pass print(D().hi()) print([k.__name__ for k in D.__mro__])
Context managers, exceptions, and the rest
Model answer: context managers
A context manager sets something up and guarantees cleanup, used with with. It defines __enter__ (setup, its return value goes to as) and __exit__ (cleanup, runs even if an exception is raised; returning True suppresses the exception). with open(path) as f: closes the file no matter what. You can write one quickly with @contextlib.contextmanager and a yield inside try/finally.
Model answer: exception handling
Use try / except SpecificError / else / finally. else runs only if no exception was raised; finally always runs. Catch the narrowest exception you can handle; a bare except: also catches KeyboardInterrupt and SystemExit. Re-raise with raise to keep the traceback, and chain with raise NewError(...) from err. Custom exceptions subclass Exception. Python 3.11 added ExceptionGroup and except* for handling several errors at once (used by asyncio.TaskGroup).
Model answer: type hints
Type hints (def f(x: int) -> str:) are not enforced at runtime; the interpreter ignores them. Static checkers like mypy or pyright read them to catch bugs before running, editors use them for autocomplete, and libraries like Pydantic and FastAPI read them at runtime to validate data. Modern syntax: list[int], dict[str, int], int | None, and since 3.12 generic syntax like def first[T](xs: list[T]) -> T:.
Model answer: virtual environments
A virtual environment is an isolated folder with its own Python interpreter link and its own site-packages, so each project has its own dependency versions without conflicts. Create one with python -m venv .venv and activate it, or use uv (uv venv, uv add), which is now very common because it is much faster. Dependencies are declared in pyproject.toml and pinned in a lock file. Never commit the .venv folder.
Match the question to the key phrase of a strong answer.
- mutable
- An object that can be changed in place, like a list, dict, or set.
- hashable
- Has a hash that never changes and matches for equal objects, so it can be a dict key or set member.
- GIL
- CPython's Global Interpreter Lock: only one thread runs Python bytecode at a time.
- generator
- A function with
yieldthat produces values lazily, one at a time, keeping its state between them. - MRO
- Method resolution order: the order Python searches classes for an attribute, via C3 linearization.
- context manager
- An object with
__enter__and__exit__used inwith, guaranteeing cleanup.