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?
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?
What's the difference between a shallow copy and a deep 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?
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?
How does a dict work, and what's its time complexity?
When do you use a set?
|, & 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?
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?
UnboundLocalError if you read it before assigning. global and nonlocal change that.What is a closure, and what is the late-binding gotcha?
[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?
@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?
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?
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?
__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?
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?
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?
__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?
How do you manage dependencies and environments?
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.Keep preparing
Python shallow copy vs deep copy: trace a nested-data bug
Follow a nested dictionary through assignment, shallow copying and deep copying, then choose the right copying boundary for a data workflow.
ArticlePython projects for beginners: three small programs with complete code
Build three beginner Python projects with complete code: a study tracker, quiz report and CSV stock checker. Check the output, then extend each one.
ArticlePython for machine learning and AI: what to learn first, and what to skip
Learn core Python first, then NumPy, pandas, Matplotlib and scikit-learn, in that order. What each stage gives you, what to skip and when you know enough.
Interview prep24 NumPy interview questions
NumPy interview questions on arrays, dtypes, views and copies, broadcasting, vectorisation and linear algebra: the foundations every data science library is built on.
Interview prep26 pandas interview questions
pandas interview questions on indexing, cleaning, groupby, merges, reshaping and performance, including the warnings and silent bugs interviewers love to ask about.
Interview prep24 Jupyter interview questions
Jupyter Notebook and JupyterLab questions for data roles: kernels, hidden state, magics, environments, version control and when a notebook should become real code.
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.