Python interview questions

18 Python interview questions and answers

Python questions for backend, data and automation roles: how the language works under the hood, the idioms interviewers expect and the pitfalls that catch people out. Each question has a short answer, a deeper explanation, code and likely follow-ups.

18 questions with a 30-second answer, a deeper explanation and the follow-ups interviewers usually ask.

How to use these questions

Python interviews usually test three things. First, the data model: mutable and immutable types, equality versus identity, hashing, copying and what happens with default arguments. Second, idiomatic features: decorators, generators, context managers, dataclasses and type hints. Third, how Python runs: the GIL, memory management and the choice between threads, processes and asyncio.

Many of the best questions are small traps: why does a function with a list as a default argument remember its previous calls, why does is sometimes appear to work for numbers, why can a thread pool speed up downloads but not number crunching. If you can explain the reason, not only the rule, you will handle the variations.

Work through the questions in order, say each answer aloud, then run the code samples yourself and change them. Questions marked Often asked are the best use of limited time.

Python

Internals, decorators, generators and the GIL

Q1EasyFresher

List vs tuple - what is the difference?

30-second answer: Lists can change, tuples cannot. Tuples can be dictionary keys and signal a fixed record.

Lists are mutable and tuples are immutable. Tuples are hashable when their contents are, so they can be dictionary keys or set members, and they signal "fixed record" to the reader.

Follow-up questions interviewers ask next

  • Are tuples always faster than lists?
  • Can a tuple hold a mutable object?
Q2HardSeniorOften asked

What is the GIL and how does it affect concurrency?

30-second answer: The GIL lets only one thread run Python bytecode at a time. Threads help I/O-bound work, not CPU-bound work - use multiprocessing for that.

The Global Interpreter Lock lets only one thread execute Python bytecode at a time in CPython. Threads therefore do not speed up CPU-bound work, but they work well for I/O-bound tasks because the lock is released while waiting.

For CPU-bound work use multiprocessing, native extensions (NumPy), or a different runtime.

Follow-up questions interviewers ask next

  • What changes with free-threaded Python?
  • When would you pick asyncio over threads?
Q3Medium2–5 years

How do decorators work?

30-second answer: A decorator takes a function and returns a wrapped version with extra behaviour. @dec is shorthand for f = dec(f). Use functools.wraps to keep the name and docstring.

A decorator is a function that takes a function and returns a replacement, usually wrapping the original with extra behaviour. @dec above a definition is shorthand for f = dec(f).

Python
import functools, time

def timed(fn):
    @functools.wraps(fn)
    def wrapper(*a, **kw):
        t = time.perf_counter()
        try:
            return fn(*a, **kw)
        finally:
            print(fn.__name__, time.perf_counter() - t)
    return wrapper
JavaScript
function timed(fn) {
  return (...args) => {
    const t = performance.now();
    try {
      return fn(...args);
    } finally {
      console.log(fn.name, performance.now() - t);
    }
  };
}

Follow-up questions interviewers ask next

  • How do you write a decorator that takes arguments?
  • What are class-based decorators?
Q4Medium2–5 years

Generators vs lists - why use yield?

30-second answer: A generator yields values one at a time instead of building the whole list, so memory stays flat. Use it to stream big files.

A generator produces values lazily, one at a time, so memory stays constant regardless of how many items it yields. Use it to stream large files or infinite sequences.

Python
def read_lines(path):
    with open(path) as f:
        for line in f:
            yield line.rstrip()

for row in read_lines("big.log"): ...
JavaScript
function* readLines(lines) {
  for (const line of lines) yield line.trim();
}

for (const row of readLines(data)) {  }

Follow-up questions interviewers ask next

  • Generator vs iterator - what is the difference?
  • What does yield from do?
Q5EasyFresher

What is the difference between is and == in Python?

30-second answer: == asks whether two objects have equal values; is asks whether they are the same object. Use is only for None and other singletons.

== compares values by calling __eq__. is compares identity: whether two names refer to the very same object in memory.

Use == to compare values and is only for singletons such as None (if x is None). CPython caches small integers and some strings, so a is b can be True for equal small values, but that is an implementation detail you should never rely on.

a = [1, 2]
b = [1, 2]
a == b      # True: same values
a is b      # False: two different list objects

x = None
x is None   # the idiomatic check

Follow-up questions interviewers ask next

  • Why can two equal small integers satisfy is?
  • How do you define equality for your own class?
Q6EasyFresherOften asked

What is the mutable default argument problem?

30-second answer: Defaults are created once at definition time, so a mutable default like a list is shared by every call. Use None as the default and build the list inside the function.

Default argument values are evaluated once, when the function is defined, not each time it is called. If the default is a mutable object such as a list or dict, every call that uses the default shares the same object, so changes persist between calls.

Use None as the default and create the object inside the function.

def add_item(item, items=[]):       # bug: one list shared by all calls
    items.append(item)
    return items

def add_item_fixed(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items

Follow-up questions interviewers ask next

  • Where can you see the stored default value?
  • Is the same problem possible with class attributes?
Q7EasyFresher

What are *args and **kwargs?

30-second answer: *args gathers extra positional arguments into a tuple and **kwargs gathers extra keyword arguments into a dict. In a call, * and ** unpack them again.

*args collects extra positional arguments into a tuple and **kwargs collects extra keyword arguments into a dict. Using them in a call does the opposite: f(*items, **options) unpacks a sequence and a mapping into arguments.

They are common in decorators and wrappers that must forward whatever arguments they receive, and in APIs with optional configuration. Prefer explicit parameters when the function has a fixed, known interface, because they are easier to read and document.

def log_call(func):
    def wrapper(*args, **kwargs):
        print('calling', func.__name__, args, kwargs)
        return func(*args, **kwargs)
    return wrapper

Follow-up questions interviewers ask next

  • What is the required order of parameters in a function signature?
  • How do keyword-only arguments work?
Q8Medium2–5 years

How do dictionaries and sets work internally, and what is their time complexity?

30-second answer: Dicts and sets are hash tables, so lookup, insert and delete are O(1) on average and keys must be hashable. Checking membership in a set is far faster than in a list.

A dict is a hash table. Python hashes the key to find a slot, so lookups, inserts and deletes are O(1) on average. Keys must be hashable, which in practice means immutable types such as strings, numbers and tuples of hashables; lists and dicts cannot be keys.

Since Python 3.7 dicts preserve insertion order. A set uses the same hash-table idea for membership tests, which is why x in some_set is much faster than x in some_list for large collections: O(1) on average versus O(n).

Follow-up questions interviewers ask next

  • What happens when two keys have the same hash?
  • Why can't a list be a dict key?
Q9HardSenior

How does Python manage memory?

30-second answer: CPython frees objects when their reference count drops to zero, and a cyclic garbage collector handles reference cycles. Use weak references for caches that shouldn't keep objects alive.

CPython manages memory mainly with reference counting: each object tracks how many references point to it and is freed when the count reaches zero. Reference counting cannot free reference cycles (objects that refer to each other), so CPython also runs a cyclic garbage collector periodically to find and collect them.

Objects live on a private heap managed by Python's allocator, and the gc module lets you inspect or tune collection. Practical consequences: avoid needless cycles in long-running code, release large objects when finished and use weakref for caches that should not keep objects alive.

Follow-up questions interviewers ask next

  • What is a reference cycle and how can you create one?
  • What does sys.getrefcount show?
Q10Easy2–5 years

What is the difference between a shallow copy and a deep copy?

30-second answer: Assignment shares the object, a shallow copy duplicates only the outer container, and deepcopy duplicates every level. Shallow copies still share nested objects.

Assignment (b = a) only creates another name for the same object. copy.copy or list(a) makes a shallow copy: a new outer container that still references the same inner objects. copy.deepcopy recursively copies everything.

With a shallow copy of a list of lists, changing an inner list through the copy also changes the original. Use deepcopy when you need full independence, and remember it is slower and can be surprising for objects that hold external resources.

import copy

rows = [[1, 2], [3, 4]]
shallow = copy.copy(rows)
deep = copy.deepcopy(rows)

rows[0].append(99)
shallow[0]   # [1, 2, 99]  (shares the inner list)
deep[0]      # [1, 2]      (independent)

Follow-up questions interviewers ask next

  • What does copy.copy do for an immutable tuple?
  • How can a class customise how it is copied?
Q11Medium2–5 years

What are context managers and the with statement?

30-second answer: A context manager runs setup on entering a with block and guaranteed cleanup on leaving it, even after an exception. Write one with __enter__ and __exit__, or with contextlib.contextmanager.

A context manager defines setup and cleanup around a block of code with the with statement. On entry it runs __enter__; on exit, even if an exception occurred, it runs __exit__. The classic example is a file that is always closed.

You can write one as a class with those two methods or, more simply, with the @contextmanager decorator from contextlib around a generator that yields once. Use them for resources that must be released: files, locks, database connections and temporary changes of state.

from contextlib import contextmanager
import time

@contextmanager
def timer(label):
    start = time.perf_counter()
    try:
        yield
    finally:
        print(label, round(time.perf_counter() - start, 3), 's')

with timer('load'):
    load_data()

Follow-up questions interviewers ask next

  • What arguments does __exit__ receive?
  • How can a context manager suppress an exception?
Q12EasyFresher

What is the difference between instance methods, class methods and static methods?

30-second answer: Instance methods get self, class methods get cls and suit alternative constructors, and static methods get neither and are just namespaced functions.

An instance method takes self and works with one object's data. A class method, marked with @classmethod, takes cls and works with the class, which makes it a good fit for alternative constructors. A static method, marked with @staticmethod, takes neither; it is a plain function grouped inside the class for organisation.

Class methods respect inheritance (cls is the subclass when called on one), which is the main reason to prefer them over static methods for factory functions.

class User:
    def __init__(self, name, email):
        self.name, self.email = name, email

    @classmethod
    def from_dict(cls, data):
        return cls(data['name'], data['email'])

    @staticmethod
    def is_valid_email(value):
        return '@' in value

Follow-up questions interviewers ask next

  • Why use a class method as a factory?
  • Can a static method access instance data?
Q13Medium2–5 yearsOften asked

When do you use threading, multiprocessing and asyncio?

30-second answer: Use asyncio or threads when the work is waiting on I/O, and multiprocessing when it is CPU-bound, because the GIL stops threads running Python code in parallel.

Use asyncio for many concurrent I/O waits such as network calls: it runs tasks on one thread and switches at await points. Use threading for I/O-bound work that relies on blocking libraries; threads overlap their waiting, but the GIL stops them running Python bytecode in parallel. Use multiprocessing (or ProcessPoolExecutor) for CPU-bound work, because separate processes have separate interpreters and can use several cores.

Processes cost more memory and need data to be passed between them. A simple rule: waiting on the network, use asyncio or threads; crunching numbers, use processes or native libraries such as NumPy. Experimental free-threaded builds change this picture, but most code still runs with the GIL.

Follow-up questions interviewers ask next

  • Why can a thread pool speed up downloads but not number crunching?
  • How do you share data between processes?
Q14EasyFresher

What are __repr__ and __str__, and what other dunder methods matter?

30-second answer: __repr__ is the developer-facing, unambiguous representation and __str__ is the user-friendly one; str() falls back to __repr__. Other dunders like __len__ and __eq__ hook your class into built-ins.

Dunder (double underscore) methods let your classes plug into Python's syntax and built-ins: __init__ initialises an object, __len__ powers len(), __eq__ powers == and __iter__ makes an object iterable.

__repr__ should return an unambiguous string for developers, ideally one that looks like the code to recreate the object; __str__ returns a readable string for users. If only __repr__ is defined, str() falls back to it, so define __repr__ first.

class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y

    def __repr__(self):
        return f'Point({self.x}, {self.y})'

    def __eq__(self, other):
        return (self.x, self.y) == (other.x, other.y)

Follow-up questions interviewers ask next

  • Which method does a list use when it prints its items?
  • What is the relationship between __eq__ and __hash__?
Q15Easy2–5 years

How do you handle exceptions properly in Python?

30-second answer: Catch the narrowest exception you can actually handle, use else for the success path and finally for cleanup, and chain errors with raise from. Avoid bare except.

Use try for code that may fail, except to handle specific exception types, else for code that should run only if no exception occurred and finally for cleanup that must always run. Catch the narrowest exception you can handle; a bare except: also swallows KeyboardInterrupt and hides bugs.

Raise exceptions with raise, and use raise NewError(...) from err to keep the original cause. Define a custom exception class for errors specific to your domain so callers can catch them precisely.

class ConfigError(Exception):
    pass

def load_port(raw):
    try:
        port = int(raw)
    except ValueError as err:
        raise ConfigError(f'invalid port: {raw!r}') from err
    else:
        return port
    finally:
        print('parsed config value')

Follow-up questions interviewers ask next

  • Why is catching Exception everywhere a problem?
  • When does the else block of a try statement run?
Q16Medium2–5 years

What are type hints and do they affect runtime behaviour?

30-second answer: Type hints describe expected types but Python doesn't enforce them at run time. Type checkers, editors and libraries like Pydantic use them to catch bugs and generate behaviour.

Type hints annotate the expected types of arguments, return values and variables, such as def total(prices: list[float]) -> float. Python does not enforce them at run time; they are metadata used by tools such as mypy and pyright, by editors for completion and by libraries such as Pydantic and FastAPI.

They catch whole classes of bugs before the code runs and double as documentation. Adopt them gradually, starting with function signatures in public code, and run a type checker in CI.

def total(prices: list[float], tax: float = 0.0) -> float:
    return sum(prices) * (1 + tax)

total(['a'])   # runs, but a type checker flags it

Follow-up questions interviewers ask next

  • What is the difference between Optional[int] and int | None?
  • How would you introduce type checking to an existing codebase?
Q17HardSenior

What is the method resolution order and how does super() work?

30-second answer: The MRO is the linear order Python searches classes, computed by C3. super() calls the next class in that order, not necessarily the direct parent, which makes cooperative multiple inheritance work.

The method resolution order (MRO) is the order in which Python searches base classes for an attribute. It uses the C3 linearisation, which keeps each class before its parents and preserves the order in which bases are listed. You can see it with ClassName.__mro__.

super() does not mean "the parent": it means "the next class in the MRO". That is what makes cooperative multiple inheritance work, as long as every class calls super() in the methods it overrides.

class A:
    def hello(self): print('A')
class B(A):
    def hello(self): print('B'); super().hello()
class C(A):
    def hello(self): print('C'); super().hello()
class D(B, C):
    def hello(self): print('D'); super().hello()

D.__mro__    # D, B, C, A, object
D().hello()  # D, B, C, A

Follow-up questions interviewers ask next

  • What is the diamond problem and how does the MRO solve it?
  • What happens if one class in the chain forgets to call super()?
Q18Medium2–5 years

What are dataclasses and when should you use them?

30-second answer: A dataclass generates __init__, __repr__ and __eq__ from annotated fields, cutting boilerplate for data-holding classes. Use frozen for immutability and default_factory for mutable defaults.

A dataclass is a class decorated with @dataclass that generates __init__, __repr__ and __eq__ from its annotated fields, which removes boilerplate for classes that mainly hold data. Options include frozen=True for immutable instances, order=True for comparison methods and field(default_factory=list) for mutable defaults.

Use a dataclass for simple records, a plain class when you need custom behaviour and a library such as Pydantic when you need validation of external data.

from dataclasses import dataclass, field

@dataclass(frozen=True)
class Order:
    id: int
    items: tuple = ()
    notes: str = ''

@dataclass
class Cart:
    lines: list = field(default_factory=list)

Follow-up questions interviewers ask next

  • Why do you need default_factory for a list field?
  • How do dataclasses compare with Pydantic models?

How to prepare for a Python interview

  1. Write the idioms from memory. A decorator with functools.wraps, a generator pipeline, a context manager and a dataclass. If you can type them without looking, you understand them.
  2. Know the standard library. collections (Counter, defaultdict, deque), itertools, functools and pathlib solve many interview problems in a few lines.
  3. Practise problems in Python. Solve data structure and algorithm problems with built-in types and state the complexity of each operation. Use DSA practice.
  4. Be ready for data-role questions. If the role touches data, expect pandas and SQL questions next.
  5. Explain trade-offs. For concurrency, say what the work is bound by (network or CPU) before you pick threads, processes or asyncio.

Avoid answering with "it depends" and stopping. Say what it depends on and give the choice for each case.