ExtraBrain Interview Questions

Python Interview Questions for 2026, With Tested Answers

Short answer

Expect Python interviews to center on how the language behaves: mutable default arguments, late-binding closures, generators, decorators, and building small data structures such as an LRU cache. Newer rounds add asyncio (TaskGroup, timeouts, bounded concurrency) and what the free-threaded build changes about the GIL. Show the code, predict its output before running it, and explain the fix.

Python interview questions for 2026: mutable defaults, closures, generators, decorators, an LRU cache, asyncio and free-threading, with tested code.

  • Python
  • Coding Interviews
  • Technical Interviews

Python rounds rarely ask you to recite definitions. They show you five lines of code and ask what it prints, or ask you to build something small, such as a retry decorator or an LRU cache, and then change a requirement halfway through. The questions below are the ones that keep appearing, with answers you can say out loud and code that has been run on Python 3.14.

Version questions have also become fair game. Python 3.14 made the free-threaded build officially supported, and Python 3.15.0 shipped on October 9, 2026. You don’t need every release note, but you should know what changed about threads.

Language behavior questions

Why does this function remember values between calls?

def add_tag(tag, tags=[]):
tags.append(tag)
return tags
print(add_tag("a")) # ['a']
print(add_tag("b")) # ['a', 'b'], the same list again
def add_tag_fixed(tag, tags=None):
if tags is None:
tags = []
tags.append(tag)
return tags
print(add_tag_fixed("a"), add_tag_fixed("b")) # ['a'] ['b']

The Python programming FAQ explains it: default values are evaluated once, when the function is defined, so a mutable default is shared by every call that uses it. Use None as the default and create the object inside the function.

Why do all these lambdas return the same number?

squares = [lambda: x ** 2 for x in range(4)]
print([f() for f in squares]) # [9, 9, 9, 9]
squares = [lambda x=x: x ** 2 for x in range(4)]
print([f() for f in squares]) # [0, 1, 4, 9]

A closure looks up x when it is called, not when it is created, and by then the loop has finished with x equal to 3. Binding the current value as a default argument, as the same FAQ shows, captures it at definition time. functools.partial is the other common fix.

What is a generator, and when would you use one?

A generator produces values lazily, one per next() call, so it can represent a sequence too large to hold in memory:

from itertools import batched, islice
def read_events(n):
for i in range(n):
yield {"id": i} # produced on demand, never all at once
print(list(islice(read_events(10**9), 3))) # [{'id': 0}, {'id': 1}, {'id': 2}]
print(list(batched(range(7), 3))) # [(0, 1, 2), (3, 4, 5), (6,)]

Mention that a generator can be consumed only once, and that itertools.batched, added in 3.12, is the standard way to chunk work into batches. Since 3.13 it accepts strict=True to reject a short final batch.

Write a retry decorator.

import functools
def retry(times):
def decorator(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
for attempt in range(1, times + 1):
try:
return fn(*args, **kwargs)
except ConnectionError:
if attempt == times:
raise
return wrapper
return decorator
calls = {"n": 0}
@retry(times=3)
def flaky_fetch():
"""Fails twice, then succeeds."""
calls["n"] += 1
if calls["n"] < 3:
raise ConnectionError("try again")
return "ok"
print(flaky_fetch(), calls["n"]) # ok 3
print(flaky_fetch.__name__, flaky_fetch.__doc__) # flaky_fetch Fails twice, then succeeds.

Explain the three layers (the argument, the decorator, the wrapper) and why functools.wraps matters: without it, the function’s name and docstring become the wrapper’s, which breaks logging and debugging. Good follow-ups to raise yourself: retry only exceptions that are safe to retry, and add backoff between attempts.

Data structure questions

Implement an LRU cache with O(1) get and put.

from collections import OrderedDict
class LRUCache:
def __init__(self, capacity):
self.capacity = capacity
self.data = OrderedDict()
def get(self, key):
if key not in self.data:
return -1
self.data.move_to_end(key) # mark as most recently used
return self.data[key]
def put(self, key, value):
if key in self.data:
self.data.move_to_end(key)
self.data[key] = value
if len(self.data) > self.capacity:
self.data.popitem(last=False) # evict the least recently used
cache = LRUCache(2)
cache.put("a", 1)
cache.put("b", 2)
cache.get("a") # "a" becomes most recent
cache.put("c", 3) # evicts "b"
print(list(cache.data)) # ['a', 'c']
print(cache.get("b")) # -1

If the interviewer bans OrderedDict, the classic version is a dict pointing to nodes in a doubly linked list. For production code, mention functools.lru_cache. Our page on cache eviction policies covers LRU against LFU and TTL if the conversation turns to system design.

What makes an object usable as a dict key?

A dict is a hash table, so a key needs a __hash__ that never changes during its lifetime and an __eq__ that agrees with it: objects that compare equal must hash equal. That is why lists can’t be keys and tuples of hashable items can. For your own types, a frozen dataclass gives you both methods for free:

from dataclasses import dataclass
@dataclass(frozen=True)
class Point:
x: int
y: int
grid = {Point(1, 2): "start"} # frozen dataclasses are hashable
print(grid[Point(1, 2)]) # start
key = [1, 2]
try:
grid[key] = "oops"
except TypeError as err:
print(err) # unhashable type: 'list' (the exact wording varies by version)

Lookups are O(1) on average and degrade when many keys collide, which is the follow-up interviewers use to check you understand hashing rather than just the syntax.

Write a context manager.

A context manager guarantees cleanup, which is why files, locks and database transactions use with. The shortest correct version uses contextlib.contextmanager, with the cleanup in finally so it runs even when the body raises:

import time
from contextlib import contextmanager
@contextmanager
def timer(label):
start = time.perf_counter()
try:
yield
finally:
print(f"{label} took {time.perf_counter() - start:.1f}s")
with timer("sleep"):
time.sleep(0.2) # prints: sleep took 0.2s

Be ready to write the class form too, with __enter__ and __exit__, and to say what returning True from __exit__ does: it suppresses the exception, which is rarely what you want.

Quick-fire questions

QuestionShort answer
is vs ==Identity vs equality; use is for None
List vs tupleMutable vs immutable; hashable tuples can be dict keys
Shallow vs deep copycopy.copy copies the container only
*args and **kwargsExtra positional args as a tuple, keywords as a dict
__slots__Fixed attributes, no per-instance __dict__

Concurrency questions

Run many I/O calls with a concurrency limit and a timeout.

import asyncio
async def fetch(i, sem):
async with sem:
await asyncio.sleep(0.1) # stands in for a network call
return i * 10
async def main():
sem = asyncio.Semaphore(3) # at most 3 calls in flight
async with asyncio.timeout(2):
async with asyncio.TaskGroup() as tg:
tasks = [tg.create_task(fetch(i, sem)) for i in range(6)]
print([t.result() for t in tasks]) # [0, 10, 20, 30, 40, 50]
asyncio.run(main())

The asyncio task docs give you the talking points. If one task in a TaskGroup fails, the remaining tasks are cancelled; with gather and the default return_exceptions=False, the first exception propagates but the other awaitables keep running. asyncio.timeout turns the cancellation into a TimeoutError you catch outside the block. And the event loop keeps only weak references to tasks, so a fire-and-forget create_task result you don’t store can be garbage collected mid-run.

Does Python still have a GIL?

The default build does. The free-threaded build can run without it, and 3.14’s release notes put its single-threaded slowdown at roughly 5-10% depending on platform and compiler. The free-threading HOWTO shows how to check what you’re running:

import sys
import sysconfig
print(sysconfig.get_config_var("Py_GIL_DISABLED") == 1) # True on a free-threaded build
print(sys._is_gil_enabled()) # False when the GIL is actually off

The same HOWTO notes that built-in types such as dict and list use internal locks, but recommends explicit locks rather than relying on them, and warns that sharing one iterator across threads isn’t safe. A strong answer ends with the decision in the diagram below.

Diagram matching Python workloads to concurrency tools: many network waits go to asyncio with TaskGroup and timeouts, blocking I/O libraries go to a thread pool, CPU-bound work on the standard build goes to a process pool, CPU-bound work on the free-threaded build can use threads after measuring, and hot numeric loops go to NumPy or native extensions

Version questions worth a minute of prep

ReleaseChangeLikely question
3.14 (Oct 2025)Free-threaded build supported”Would you remove multiprocessing?“
3.14Template strings (t"...")“How do t-strings help with SQL safety?“
3.15 (Oct 2026)Explicit lazy imports (PEP 810)“How would you cut CLI startup time?“
3.15UTF-8 default encoding (PEP 686)“Why might a file read change?”

The 3.15 release notes also add a built-in frozendict and a sampling profiler in the new profiling package. Treat these as conversation, not code you’ll be asked to write.

Practice saying the output first

The habit that separates strong Python candidates is predicting output before running anything. Rehearse that out loud: read a snippet, say what it prints and why, then run it. ExtraBrain can transcribe those practice sessions so you can check whether your explanation matched the result, and the backend developer mock interview page has prompts for the rounds around the coding one. In a live interview, use ExtraBrain only where the employer’s rules allow AI assistance.

Sources (checked November 23, 2026)

FAQ

Which Python version should I use in a coding interview?

Whatever the platform provides, usually a recent 3.x. Avoid features newer than 3.12 unless you know the environment supports them.

Do I need to know asyncio for a general backend role?

Know the basics: what an event loop is, when async helps (many I/O waits) and when it doesn’t (CPU-bound work). Deeper questions come up mainly for services built on async frameworks.

Are type hints expected?

They aren’t required in most coding rounds, but adding them to function signatures makes your code easier to discuss and is common in production Python.

I’m interviewing for an AI role. What Python comes up?

The same language questions, plus code around models: batching requests, async calls to an API with limits and timeouts, and small evaluation scripts. Our LLM engineer interview questions include Python you can practice with.

What is a common Python mistake in interviews?

Mutating a list while iterating over it, along with the mutable default argument shown above. Removing items inside a for loop shifts the remaining elements, so the loop silently skips some of them. Build a new list with a comprehension instead, or iterate over a copy. Changing a dict’s size during iteration is louder: Python raises a RuntimeError.