Interview prep

28 Python interview questions, with answers.

Python interview questions for data science, ML and backend roles: mutability, data structures, functions and scope, classes, generators, errors and the GIL, with the pitfalls interviewers probe.

Python interviews mix definitions with small puzzles that expose how the language really works: why a default argument remembers old calls, why changing one list changed another, why threads don't speed up your loop. The questions below cover the ones that come up most often in data and engineering interviews.

When you answer, give a one-line example. It proves you've hit the problem, not just read about it.

These 28 questions are free. SchoolWhool's Foundations of AI course places 650+ interview questions right after the lessons they test, with a mock interview with Gaurav. See also the machine learning interview questions.

Core language

What's the difference between mutable and immutable types?
Mutable objects can change in place: lists, dicts, sets and most custom objects. Immutable ones can't: ints, floats, strings, tuples and frozensets. It matters because only hashable (typically immutable) objects can be dict keys or set members, and because two names pointing at one mutable object see each other's changes.
What's the difference between is and ==?
== compares values, using __eq__; is checks whether two names refer to the same object. Use is only for singletons such as None: if x is None. CPython caches small integers and some strings, so is can seem to work on them; never rely on it.
How are arguments passed to functions?
By object reference, sometimes called call by sharing: the function receives a reference to the same object. Mutating a mutable argument, such as appending to a list, is visible to the caller. Rebinding the parameter name inside the function isn't.
What's the difference between a shallow copy and a deep copy?
A shallow copy (list.copy(), copy.copy, slicing) creates a new outer container that still holds references to the same inner objects. copy.deepcopy copies everything recursively. A classic trap is [[0] * 3] * 3, which creates three references to one inner list, so changing one row changes all three.
What's the mutable default argument pitfall?
Default values are evaluated once, when the function is defined, so def f(x, acc=[]) shares the same list across every call and keeps growing. Use acc=None and create the list inside: if acc is None: acc = [].
Which values are falsy?
None, False, zero of any numeric type, and empty containers and strings; almost everything else is truthy. if not items: is the idiomatic emptiness check. Use is None when zero or an empty string is a valid value, and remember that NumPy arrays and pandas Series refuse to be used as a single truth value.

Data structures

When would you use a list and when a tuple?
Lists are mutable and suit collections that change. Tuples are immutable, slightly smaller and hashable when their contents are, so they suit fixed records, function return values and dict keys. Using a tuple also signals that the data shouldn't change.
How does a dict work, and what's its time complexity?
It's a hash table: the key's hash decides where the value is stored, so lookup, insertion and deletion are O(1) on average, degrading to O(n) only with many collisions. Keys must be hashable. Since Python 3.7, dicts preserve insertion order.
When do you use a set?
For fast membership tests (O(1) on average, versus O(n) for a list), removing duplicates and set algebra with |, & and -. Sets are unordered and their elements must be hashable. Converting a list to a set before repeated in checks inside a loop is a common, easy optimisation.
What's the difference between a list comprehension and a generator expression?
[x * x for x in xs] builds the whole list in memory at once. (x * x for x in xs) produces values lazily, one at a time, using constant memory, and can only be consumed once. Prefer generators for large or streaming data, for example sum(x * x for x in xs).
What do yield and generator functions do?
A function containing yield returns a generator. Each next() call runs it until the next yield, keeping its local state between calls. Generators are ideal for reading large files line by line and building processing pipelines; yield from delegates to another generator.
Which classes from the collections module do you use?
Counter for counting, defaultdict for dicts with default values, deque for O(1) appends and pops at both ends (queues), namedtuple for lightweight records, and OrderedDict for its move_to_end, as in an LRU cache. Knowing these is a quick signal of fluency.
How do you sort by a custom key?
sorted(items, key=lambda p: p['age'], reverse=True) returns a new list; list.sort() sorts in place and returns None. Python's sort (Timsort) is stable and O(n log n), so you can sort by a secondary key first and then by the primary key. operator.itemgetter and attrgetter are fast key functions.

Functions and scope

What are *args and **kwargs?
*args collects extra positional arguments into a tuple and **kwargs collects extra keyword arguments into a dict. The same symbols unpack when calling: f(*values, **options). Parameters after a bare * are keyword-only; parameters before / are positional-only.
What is the LEGB rule?
Python resolves a name by searching Local, then Enclosing function, then Global (module), then Built-in scopes. Assigning to a name anywhere in a function makes it local there, which causes UnboundLocalError if you read it before assigning. global and nonlocal change that.
What is a closure, and what is the late-binding gotcha?
A closure is an inner function that remembers variables from its enclosing scope after the outer function returns. The gotcha: functions created in a loop capture the variable, not its value at that moment, so [lambda: i for i in range(3)] all return 2. Bind the value with a default argument: lambda i=i: i.
What is a decorator?
A function that takes a function and returns a new one that wraps it, adding behaviour such as logging, timing, caching or access checks. @decorator above a definition is shorthand for f = decorator(f). Use functools.wraps so the wrapper keeps the original name and docstring; functools.lru_cache is a built-in example.
When is a lambda appropriate?
For short, single-expression functions passed as arguments, such as a key for sorting or a simple callback. If it needs a name, a docstring or more than one expression, write a normal def, which is easier to read and debug.

Objects and classes

What's the difference between instance, class and static methods?
Instance methods receive the instance as self. A @classmethod receives the class as cls, which suits alternative constructors like from_dict and works correctly for subclasses. A @staticmethod receives neither; it's an ordinary function kept in the class's namespace.
What are dunder methods?
Special methods with double underscores, such as __init__, __repr__, __eq__, __len__, __iter__, __enter__ and __exit__, that hook your class into Python syntax and built-in functions. Always implement a helpful __repr__. If you define __eq__, define a consistent __hash__ too, or instances become unhashable.
What's the difference between __new__ and __init__?
__new__ creates and returns the instance; __init__ initialises an instance that already exists and returns None. You rarely override __new__; it's mostly used when subclassing immutable types or controlling instance creation.
How do inheritance and the method resolution order work?
A subclass inherits attributes and methods and can override them. super() calls the next class in the method resolution order, which Python computes with C3 linearisation; it matters with multiple inheritance. Prefer composition when the relationship is has-a rather than is-a.
What are dataclasses?
@dataclass generates __init__, __repr__ and __eq__ from type-annotated fields, removing boilerplate. Options include frozen=True (immutable and hashable), order=True and slots=True. Use field(default_factory=list) for mutable defaults; a plain [] default raises an error.
What is @property for?
It exposes a method as an attribute, so you can compute a value or validate a setter without changing the class's public interface. Callers write obj.area, not obj.area(). Keep properties cheap; heavy work hidden behind attribute access surprises people.

Errors, performance and tooling

How do try, except, else and finally work together?
except handles the exceptions you name; else runs only if nothing was raised; finally always runs, for cleanup. Catch specific exceptions; a bare except: also swallows KeyboardInterrupt and hides bugs. Use raise NewError(...) from err to keep the original cause.
What is a context manager?
An object with __enter__ and __exit__ methods, used with a with statement, that guarantees setup and cleanup even if an error occurs: closing files, releasing locks, committing or rolling back transactions. contextlib.contextmanager turns a generator function into one.
What is the GIL, and what does it mean for performance?
In CPython, the Global Interpreter Lock lets only one thread execute Python bytecode at a time. Threads therefore don't speed up CPU-bound pure-Python code, but they do help I/O-bound work like network calls. For CPU-bound work, use multiprocessing or libraries such as NumPy that release the GIL; Python 3.13 also offers an experimental free-threaded build.
How do you manage dependencies and environments?
One virtual environment per project (venv, uv or conda) and pinned versions in a lock file, such as uv.lock, poetry.lock or a fully pinned requirements.txt. Never install project packages into the system Python. Reproducible environments are the first thing that breaks when a project moves to production.

First Principles, the SchoolWhool newsletter

One machine learning idea, explained properly, every week.

The intuition, the common mistake, and a five-minute way to try it yourself. Written by Gaurav.

Learn it properly, then the interview is the easy part.

Foundations of AI teaches Python and the rest of machine learning from first principles, with notebooks that check your work.