Python backend interview prep

Python Interview Questions and Answers 2026

A focused set of Python interview questions for backend developers. Use each answer as a spoken structure: start with the concept, add a concrete example, then mention trade-offs.

Start Python mock interviewNo credit card required. 1 free session available.
Technical interview practice in EnglishA mode where non-native speakers can practice passing technical interviews.

Core Python Data Model

1What built-in data types does Python have, and which are mutable?

Python has scalar types such as NoneType, bool, int, float and complex; text and binary types such as str, bytes and bytearray; sequence types such as list, tuple and range; and collection types such as dict, set and frozenset. The important interview distinction is mutability: list, dict, set and bytearray can change in place, while numbers, bool, str, bytes, tuple, range, frozenset and None are immutable. A useful nuance is that a tuple's own element references are fixed, but a referenced mutable object's internal state can still change.

Try answering this question with an AI coach

2How do list, tuple, set and dict differ in real code?

A list is an ordered mutable sequence, so it is good for queues of work, collected results and ordered data that changes. A tuple is ordered but immutable, so it is useful for fixed records, function returns and values that should not be reassigned. A set stores unique hashable objects and is ideal for membership checks or deduplication. A dict maps hashable keys to values and is the normal structure for indexes, lookups and JSON-like data. In modern Python, dict preserves insertion order, but its main purpose is still key-based access.

items = ["a", "b", "a"]
unique = set(items)
index = {"user_id": 42}
point = (10, 20)
Try answering this question with an AI coach

3What is the difference between is and ==?

== asks whether two objects are equal by value, usually through __eq__. is asks whether two references point to the exact same object in memory. In production code, is should usually be reserved for singleton checks such as value is None, value is True only when identity really matters, or sentinel objects. Do not rely on implementation details such as small integer caching or string interning; those can make is appear to work in examples while being the wrong semantic choice.

value = None

if value is None:
    print("missing")
Try answering this question with an AI coach

4What is a hashable object and why does it matter?

A hashable object has a hash value that remains stable during its lifetime and equality behavior consistent with that hash. Hashability matters because dict keys and set elements depend on it. Most immutable built-ins are hashable, but not all objects inside an immutable container automatically become hashable: a tuple containing a list is not hashable. In interviews, connect this to design: if an object is used as a key, fields that participate in __eq__ or __hash__ must not change after insertion, or the object can become unreachable in a dict or set.

Try answering this question with an AI coach

5How does slicing work, including negative indexes and steps?

A slice sequence[start:stop:step] includes start, excludes stop and moves by step. Missing boundaries are inferred from the direction of the step. Negative indexes count from the end, so s[-1] is the last item. A negative step walks from right to left; s[::-1] creates a reversed sequence for many sequence types. The trade-off is that slicing often creates a new object, so it is expressive but not always free for large data.

text = "interview"

print(text[1:5])
print(text[::-1])
Try answering this question with an AI coach

Functions and Scope

6Why can a Python function return progressively larger results when a default list parameter is appended to on successive calls?

In def add(value, items=[]), the empty list is created when that def statement executes, not each time the function is called. Calls that omit items therefore share the same list; appending one value on every call makes later results contain earlier values too. The usual fix is def add(value, items=None), followed by if items is None: items = [], before appending. That creates a new list only when the argument is omitted or explicitly None under this contract. A separate sentinel is useful if None itself is a meaningful input. I would avoid items = items or [] because that also replaces an intentionally supplied empty list. Mutable defaults are not inherently forbidden if shared state is deliberate, but such ownership should be explicit and tested, rather than an accidental consequence of a default parameter.

Try answering this question with an AI coach

7How do you write a decorator that accepts configuration arguments?

Write an outer function that accepts options and returns a decorator. The decorator receives the original function and returns a wrapper; the wrapper uses the captured options and forwards arguments and the return value. Apply functools.wraps to preserve metadata. For an async target, use a wrapper that awaits it if the added behavior must surround async execution.

Try answering this question with an AI coach

8What are *args and **kwargs used for?

*args collects extra positional arguments into a tuple, while **kwargs collects extra keyword arguments into a dict. They are useful for wrappers, decorators, flexible APIs and forwarding calls. At the call site, *iterable expands positional values and **mapping expands keyword values. The trade-off is clarity: explicit parameters are better when the function has a stable public contract, while args and kwargs are better at boundaries where forwarding or compatibility matters.

def call_api(path, *args, **kwargs):
    print(path, args, kwargs)

call_api("/users", 1, 2, timeout=5)

values = [1, 2]
options = {"timeout": 5}
call_api("/users", *values, **options)
Try answering this question with an AI coach

9How does Python resolve variable names with LEGB?

Python looks for names in Local, Enclosing, Global and Builtins scopes. Reading a name follows that order. Assigning a name inside a function normally creates a local binding, which is why code can raise UnboundLocalError if it reads a name before local assignment. global redirects assignment to module scope, and nonlocal redirects assignment to an enclosing function scope. In good production code, use both sparingly because they make state flow less obvious.

total = 0

def add(value):
    global total
    total += value

def counter():
    count = 0

    def increment():
        nonlocal count
        count += 1
        return count

    return increment
Try answering this question with an AI coach

10What is a closure and what is late binding?

A closure is a function that keeps access to variables from an enclosing scope after that outer function has returned. This is useful for decorators, callback factories and configured functions. Late binding means the free variable is looked up when the inner function is called, not when it is created. Lambdas created in a loop can all see the final loop value. Capture the current value with a default argument, for example lambda i=i: i, or use a small factory function.

callbacks = []

for i in range(3):
    callbacks.append(lambda: i)

print([callback() for callback in callbacks])  # [2, 2, 2]

callbacks = []
for i in range(3):
    callbacks.append(lambda i=i: i)

print([callback() for callback in callbacks])  # [0, 1, 2]
Try answering this question with an AI coach

OOP, Iteration and Resource Management

11How does method resolution order (MRO) work with multiple inheritance in Python, and how do you inspect it when debugging unexpected method calls?

For normal class-based method lookup, Python follows the class's method resolution order, or MRO, computed using C3 linearization. The first definition found along that order is selected. A subclass takes precedence over its ancestors, declared base order constrains precedence, and C3 preserves a consistent ordering through multiple inheritance, including diamonds. For class D(B, C), where B and C both derive from A and impose no conflicting order, the MRO is D, B, C, A, object. A hierarchy with incompatible ordering constraints is rejected with TypeError. I inspect D.__mro__ or D.mro() rather than guess. super() continues lookup after the current class in the actual instance's MRO; it does not mean a permanently chosen immediate parent. Cooperative methods therefore need compatible calling conventions and should consistently delegate with super when the design expects every class in the chain to participate.

class A:
    def process(self):
        return "A"

class B(A):
    def process(self):
        return f"B -> {super().process()}"

class C(A):
    def process(self):
        return f"C -> {super().process()}"

class D(B, C):
    def process(self):
        return f"D -> {super().process()}"

print("MRO:", [cls.__name__ for cls in D.__mro__])
print("Call output:", D().process())
Try answering this question with an AI coach

12How do inheritance, MRO and super() work?

Python resolves attributes through the Method Resolution Order, which is visible with ClassName.__mro__. In single inheritance it is straightforward, but in multiple inheritance Python uses C3 linearization to create a consistent order. super() does not mean 'call my parent' exactly; it means 'call the next implementation in the MRO'. That makes cooperative multiple inheritance possible when methods accept compatible arguments and each class calls super() correctly.

class A:
    def save(self):
        print("A")

class B(A):
    def save(self):
        print("B")
        super().save()

class C(A):
    def save(self):
        print("C")
        super().save()

class D(B, C):
    pass

D().save()  # B, C, A
Try answering this question with an AI coach

13What is the difference between iterable, iterator and generator?

An iterable is any object that can return an iterator from iter(), such as a list or a file object. An iterator is the stateful object that implements __next__ and raises StopIteration when exhausted. A generator is a convenient way to create an iterator with yield or a generator expression. Generators are memory-efficient because they produce values lazily, but they are usually one-shot and cannot be indexed like a list.

def read_lines(path):
    with open(path, encoding="utf-8") as file:
        for line in file:
            yield line.strip()
Try answering this question with an AI coach

14What is a context manager and why is with useful?

A context manager defines enter and exit behavior with __enter__ and __exit__, or can be created with contextlib.contextmanager. The with statement makes resource management explicit and reliable: files are closed, locks are released and transactions can commit or roll back even when exceptions happen. __exit__ receives exception information and may suppress the exception by returning true, though suppressing errors should be used carefully.

from contextlib import contextmanager

with open("data.txt", encoding="utf-8") as file:
    data = file.read()

@contextmanager
def temporary_setting():
    print("enter")
    try:
        yield
    finally:
        print("exit")
Try answering this question with an AI coach

15How do shallow copy and deep copy differ?

Assignment creates another binding to the same object; it is not a copy. A shallow copy, such as list(original), creates a new outer list whose elements still reference the original nested objects. If a = [[1], [2]] and b = a.copy(), b[0].append(3) changes the inner list visible through a, but b[0] = [9] changes only b's outer slot. copy.deepcopy recursively copies supported nested state and uses a memo to handle cycles and preserve repeated references within the copied graph. It can be expensive and may copy more than intended. Immutable objects may be reused, classes can customize copying, and external resources such as sockets or database connections do not become independent usable resources merely through deepcopy. I choose the minimum copy boundary needed for the intended ownership and mutations rather than treating deep copy as a universal isolation mechanism.

from copy import copy, deepcopy

original = [[1], [2]]
shallow = copy(original)
deep = deepcopy(original)

original[0].append(99)

print(shallow)  # [[1, 99], [2]]
print(deep)     # [[1], [2]]
Try answering this question with an AI coach

Runtime, Async and Production Code

16What does raise NewError(...) from original_error do?

raise NewError(...) from original_error raises the new exception and sets its __cause__ to the original. Python's normal traceback presentation shows the causal chain, so callers receive an appropriate higher-level error while diagnostics retain the underlying failure. For example, a repository can translate a database connection error into RepositoryUnavailable without losing why it happened. This differs from bare raise inside an except block, which re-raises the current exception. Raising a new error while handling another one without from normally creates implicit __context__; from makes the causal relationship explicit. Using from None suppresses display of the implicit context in the usual traceback presentation, although the context object may still exist. Chaining does not handle or repair the failure by itself, and the new message should avoid exposing credentials or other sensitive details.

Try answering this question with an AI coach

17How do you run blocking or CPU-heavy work from an asyncio application without stalling the event loop?

I first prefer a genuinely asynchronous library. If a blocking I/O API must be used, await asyncio.to_thread(blocking_call, argument) or submit it to a deliberately sized executor. Merely putting a synchronous call inside async def still blocks the event-loop thread. For CPU-heavy pure Python on a conventional GIL-enabled interpreter, use a process pool or a separate worker service; thread usefulness depends on whether the workload releases the GIL and on the interpreter. Bound concurrency and queueing so offloaded calls cannot exhaust threads, connections or memory. The synchronous library must be safe to use from workers, and thread-affine objects must stay on their owning thread. Set timeouts inside the blocking operation where possible: cancelling the awaiting coroutine or timing out does not forcibly stop an already running worker thread. Plan cleanup and idempotency for operations that may finish after the client has gone away.

import asyncio
import time
from concurrent.futures import ProcessPoolExecutor

def blocking_io_call():
    time.sleep(1)  # Simulates blocking disk or network operation
    return "io_done"

def heavy_cpu_calc(n):
    return sum(i * i for i in range(n))

async def main():
    # 1. Offload blocking I/O to thread pool
    io_result = await asyncio.to_thread(blocking_io_call)

    # 2. Offload CPU-heavy computation to process pool
    loop = asyncio.get_running_loop()
    with ProcessPoolExecutor() as process_pool:
        cpu_result = await loop.run_in_executor(process_pool, heavy_cpu_calc, 5_000_000)

    print(io_result, cpu_result)
Try answering this question with an AI coach

18What is async/await good for in Python web services?

async and await enable cooperative concurrency. A coroutine gives control back to the event loop when an awaited operation suspends (an already-ready await need not yield), allowing other tasks to run. This is valuable for APIs that wait on databases, HTTP calls, queues or sockets. It does not magically make CPU-bound code faster; CPU-heavy work blocks the event loop unless offloaded from the event-loop thread to an appropriate worker/process or implemented by an API that actually yields control. Synchronous native code still blocks that loop thread even if it releases the GIL. In FastAPI, a normal def endpoint is run in a thread pool, while blocking calls inside async def can block the event loop; async helps only when the call path uses non-blocking async I/O.

import asyncio

async def load_user():
    await asyncio.sleep(0.1)
    return {"id": 1}

async def main():
    user, settings = await asyncio.gather(
        load_user(),
        load_user(),
    )
    return user, settings
Try answering this question with an AI coach

19How should exceptions be handled in production Python?

Catch the most specific exception you can handle, and catch it at a layer that can recover, add context or translate it into a domain error. Avoid bare except and avoid silently swallowing errors because that hides data loss and operational problems. Use raise to re-raise the same exception and raise NewError(...) from exc to preserve causal context. Good production code also logs at boundaries, returns appropriate HTTP errors and keeps exception messages useful without leaking secrets.

try:
    result = parse_payload(payload)
except ValueError as exc:
    raise InvalidRequest("Invalid payload") from exc
Try answering this question with an AI coach

20How would you structure and test a production Python service?

Separate domain logic from framework and infrastructure code so core behavior can be tested without a server or database. Use configuration from environment or typed settings, logging instead of print, dependency injection at boundaries, and explicit timeouts for network calls. For tests, combine unit tests for pure logic, integration tests for database or external boundaries and a few end-to-end checks for critical flows. Mock external systems at clear boundaries, but test observable behavior rather than private implementation details.

Try answering this question with an AI coach

Practice Python interviews on your phone

Answer out loud and get AI feedback in the iOS or Android app.

Scan to download