Python Interview Questions for Experienced Developers

By ·

InterviewPlan AI blog cover reading "Python interview questions for experienced developers"

Experienced Python interviews check whether you understand the language beyond syntax: how objects and memory behave, generators, decorators and context managers, class design, concurrency with the GIL and asyncio, and testing. Below are 30 questions in that order, each with a short answer you can say out loud.

Which Python version to prepare for

Python ships one release a year, each October. Python 3.14 came out on 7 October 2025. Most production teams in late 2026 run somewhere between 3.10 and 3.13. Know the features that changed how people write code: match statements (3.10), faster CPython and exception groups (3.11), the new type parameter syntax (3.12), and the experimental free-threaded build (3.13, officially supported in 3.14).

1. Objects and the data model

Why is a mutable default argument a bug?

Default values are evaluated once, when the function is defined, not on every call. So def add(item, items=[]) shares one list across every call, and items pile up. Use items=None, then if items is None: items = [] inside the function. Interviewers like this one because it tests whether you know when Python evaluates code.

What is the difference between is and ==?

== compares values by calling __eq__. is checks whether two names point to the same object. Use is only for singletons such as None. A classic trap: small integers and some strings are cached, so a is b can be True for 256 and False for 257. That is an implementation detail, never something to rely on.

Shallow copy or deep copy?

A shallow copy (copy.copy, list(x), x[:]) creates a new outer container but shares the inner objects. A deep copy (copy.deepcopy) copies everything recursively. With a list of lists, changing an inner list through a shallow copy changes the original too. Deep copies are slower and can surprise you with objects that hold resources, such as file handles.

Which built-in collection would you use, and why?

List for ordered data you index, tuple for fixed records and dictionary keys, set for fast membership tests, and dict for lookups by key. Membership checks are O(1) on average for sets and dicts, and O(n) for lists. Dicts keep insertion order, guaranteed by the language since Python 3.7. For counting use collections.Counter. For queues use collections.deque, not a list.

What do *args, **kwargs and a bare * do in a signature?

*args collects extra positional arguments into a tuple. **kwargs collects extra keyword arguments into a dict. A bare * makes every parameter after it keyword-only, as in def connect(host, *, timeout=5). A / makes the parameters before it positional-only. Keyword-only parameters make call sites readable and let you reorder parameters later without breaking callers.

How does Python manage memory?

Mainly by reference counting: an object is freed as soon as nothing refers to it. A cyclic garbage collector handles reference cycles, such as two objects pointing at each other. Leaks in long-running services usually come from things still referenced: growing module-level caches, objects held in closures, or global registries. Check them with tracemalloc, which compares snapshots of where memory was allocated.

2. Functions, generators, decorators

What is a generator and why use one?

A function with yield returns a generator: it produces values one at a time and pauses between them. It uses constant memory however much data it handles, so it suits large files, database cursors and streams. A generator can only be iterated once. Generator expressions, (x for x in data), give the same laziness with list-comprehension syntax.

How does iteration actually work?

for x in obj calls iter(obj), which uses __iter__, then calls next() on the result until it raises StopIteration. Iterables give you an iterator. Iterators produce values. A list is iterable but not an iterator, which is why you can loop over it twice. A generator is its own iterator, which is why you can't.

Write a decorator that times a function.

import functools, time

def timed(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        try:
            return func(*args, **kwargs)
        finally:
            print(f"{func.__name__} took {time.perf_counter() - start:.3f}s")
    return wrapper

The detail that marks experience is functools.wraps. Without it, the wrapped function loses its name and docstring, which breaks logging, debugging and some frameworks.

What is a closure, and when do you need nonlocal?

A closure is an inner function that remembers variables from the function that created it, even after that function returned. Reading those variables just works. Assigning to one makes Python treat it as a new local variable, unless you declare it nonlocal. Name lookup follows LEGB: local, enclosing, global, built-in.

How do context managers work?

with calls __enter__ at the start and __exit__ at the end, even if an exception is raised, which guarantees cleanup. __exit__ receives the exception details and can suppress the exception by returning True. For simple cases use contextlib.contextmanager, where everything before yield is setup and the finally block after it is teardown.

3. Classes and design

What is the MRO, and how does super() use it?

The method resolution order is the order Python searches classes for an attribute, computed with C3 linearisation. You can see it with ClassName.__mro__. super() calls the next class in that order, not necessarily the parent you're thinking of. That's what makes cooperative multiple inheritance work, as long as every class calls super() with compatible arguments.

dataclass, namedtuple or Pydantic?

namedtuple is an immutable, lightweight tuple with names. @dataclass generates __init__, __repr__ and __eq__ for a normal class, and can be frozen=True or use slots=True. Pydantic validates and converts input at runtime, so it fits API boundaries and settings. A good rule: Pydantic at the edges where untrusted data enters, dataclasses inside the app.

What happens to __hash__ when you define __eq__?

Defining __eq__ without __hash__ sets __hash__ to None, so instances can no longer be dict keys or set members. That is deliberate: equal objects must have equal hashes. If the object is immutable, define __hash__ from the same fields used in __eq__. A frozen dataclass does this for you.

What are __slots__ for?

__slots__ replaces the per-instance __dict__ with fixed storage for the attributes you list. Objects use noticeably less memory and attribute access is slightly faster, which matters when you create millions of instances. The cost: no new attributes at runtime, and care is needed with inheritance.

Abstract base class or Protocol?

An ABC (abc.ABC with @abstractmethod) forces subclasses to implement methods, and fails at instantiation if they don't. A typing.Protocol describes a shape: any class with the right methods matches, without inheriting anything. That is structural typing, checked by tools such as mypy. Use a Protocol for loose coupling between modules, and an ABC when you own the hierarchy.

4. Concurrency

What is the GIL, and is it going away?

The Global Interpreter Lock lets only one thread run Python bytecode at a time in standard CPython. Threads still help with I/O, because the GIL is released while waiting, but they don't speed up CPU-bound Python code. Python 3.13 added an experimental free-threaded build without the GIL, and Python 3.14 made that build officially supported (PEP 779). It is still a separate build, not the default.

threading, multiprocessing or asyncio?

Threads suit I/O-bound work with blocking libraries. Processes suit CPU-bound work, because each process has its own interpreter and GIL, at the cost of memory and serialisation overhead. asyncio suits large numbers of concurrent network connections in one thread, but needs async-aware libraries throughout. concurrent.futures gives one interface for both threads and processes.

What goes wrong when you call blocking code inside async code?

One blocking call, such as requests.get or time.sleep, freezes the whole event loop, so every other coroutine stops. Use async libraries (httpx, asyncpg), or push the blocking call to a thread with await asyncio.to_thread(func). In FastAPI, a plain def endpoint runs in a thread pool, and an async def endpoint runs on the loop, so a blocking call inside async def hurts everyone.

How do you run several async calls at once and handle failures?

asyncio.gather runs coroutines concurrently. Pass return_exceptions=True if one failure should not cancel the rest. Since Python 3.11, asyncio.TaskGroup is the safer default: if one task fails, the others are cancelled and the errors arrive together as an ExceptionGroup, which you handle with except*. Add asyncio.timeout() so nothing hangs forever.

5. Testing, performance and tooling

How do pytest fixtures work?

A fixture is a function marked @pytest.fixture that a test requests by naming it as a parameter. Code before yield is setup and code after it is teardown. The scope setting (function, module, session) controls how often it runs, so an expensive database connection can be created once per session. Shared fixtures go in conftest.py.

Where do you patch when mocking?

Patch where the object is looked up, not where it is defined. If orders.py does from payments import charge, patch orders.charge, not payments.charge. This is the most common mocking mistake, and saying it unprompted is a strong signal.

A Python service is slow. How do you find out why?

Measure before changing anything. cProfile shows where time goes in a script. For a running production process, py-spy samples it without a restart. Then check the usual causes: N+1 database queries, repeated work that could be cached with functools.lru_cache, list lookups that should be sets, and blocking I/O inside async code.

How do you manage dependencies?

A virtual environment per project. Pin direct dependencies with a lock file, so every machine installs the same versions. Tools such as Poetry or uv manage the lock file and the environment together. Explain how you upgrade safely: one dependency at a time, run the tests, read the changelog for major versions.

6. Modern Python

When would you use a match statement?

match (Python 3.10) does structural pattern matching: it can unpack and test the shape of data in one step, such as case {"type": "card", "amount": amount}. It shines on parsed JSON, ASTs and messages with different shapes. For a simple value lookup, a dict is still clearer.

Do type hints change runtime behaviour?

No. Python ignores most annotations at runtime. Tools such as mypy or Pyright check them, and libraries like Pydantic and FastAPI read them deliberately. In large codebases, type hints catch errors before production and make refactoring safer. Python 3.14 evaluates annotations lazily by default (PEP 649), which removes most forward-reference workarounds.

What is new in Python 3.14?

Released 7 October 2025. The headline changes: the free-threaded build is officially supported (PEP 779), template strings, or t-strings, give safer string processing for things like SQL and HTML (PEP 750), annotations are evaluated lazily (PEP 649), multiple interpreters are available in the standard library (PEP 734), and there is a new compression.zstd module (PEP 784). Interviewers rarely go deep. Know what t-strings and free-threading are for.

7. Coding questions

Flatten an arbitrarily nested list.

def flatten(items):
    for item in items:
        if isinstance(item, list):
            yield from flatten(item)
        else:
            yield item

A generator with yield from keeps memory flat. Mention that very deep nesting can hit the recursion limit, and that an explicit stack avoids it.

Find the top 3 most common words in a text.

from collections import Counter
import re

top3 = Counter(re.findall(r"[a-z']+", text.lower())).most_common(3)

Then talk about edge cases: punctuation, case, and very large files, where you would count line by line instead of loading everything into memory.

Cache an expensive function.

@functools.lru_cache(maxsize=1024) memoises a pure function with hashable arguments. Know its limits: it doesn't expire entries by time, it holds references to everything cached, and on a method it also keeps self alive. For time-based caching across processes, use Redis.

How to prepare in the last 48 hours

  1. Mark the Python version and frameworks in the job description (Django, FastAPI, Flask, pandas, PySpark).

  2. Say each answer above out loud in under 90 seconds.

  3. Write the decorator, the generator and the async example from memory, without an IDE.

  4. Prepare two production stories in STAR form: a performance fix and a bug you traced. See STAR method examples.

  5. If the role is data-heavy, also go through our SQL window functions interview questions.

Practise these questions out loud with feedback in an AI mock interview. For live interviews, the InterviewPlan AI interview copilot can surface notes from your own prep on Zoom, Teams or Meet. Check your employer's rules on AI tools first.

FAQ

1. What are the most commonly asked Python interview questions?

Common Python interview questions cover mutable and immutable objects, lists and tuples, dictionaries, generators, decorators, OOP concepts, exception handling, memory management, and multithreading. Experienced roles also test asyncio, the GIL, testing, and performance optimization.

2. How should I prepare for an experienced Python developer interview?

Focus on understanding Python internals rather than memorizing syntax. Practise explaining memory management, decorators, generators, context managers, concurrency, and design patterns. Also prepare coding exercises and real-world examples from your previous projects.

3. Is Python 3.14 important for interviews in 2026?

Yes. Understanding Python 3.14 features can be useful, particularly free-threaded builds, template strings, and lazy annotation evaluation. However, you should also be comfortable with Python 3.10–3.13, as many production applications still use these versions.

4. What is the difference between threading, multiprocessing, and asyncio in Python?

Threading is generally useful for I/O-bound tasks, multiprocessing is suitable for CPU-intensive workloads, and asyncio handles large numbers of concurrent I/O operations using an event loop. Choosing the right approach depends on the workload and the libraries your application uses.

5. How can I practise Python interview questions?

Start by answering technical questions aloud, writing common coding solutions without an IDE, and practising real-world debugging scenarios. You can also use an AI mock interview to simulate interview conditions and improve your responses.

6. Are these Python interview questions suitable for senior developers?

Yes. These questions cover intermediate-to-advanced Python concepts, including memory management, object models, concurrency, async programming, architecture, testing, and performance optimization. Senior candidates should also be prepared to discuss production decisions and trade-offs.

P.S.

Reading helps. Practising out loud helps more.

Start free with 5 live minutes and 100 AI credits for Resume AI, Job Search, Auto-Apply, mock interviews and Behavioral Coach.