83 Python interview questions with answers
83 Python interview questions with detailed answers, sorted from basic to advanced. Free to practice, with progress saved automatically.
All Python interview questions
How does Python manage memory?
What are mutable vs immutable types in Python?
When to use list, tuple, set, dict?
What are generators and `yield`? Why use them?
What is a decorator? How do you write a simple one?
How does the `with` statement and context manager work?
What is a closure? How does it differ from a lambda?
Shallow copy vs deep copy — what's the difference?
How does `try/except/else/finally` work in Python?
`is` vs `==` — what's the difference?
How does `functools.lru_cache` work? When to use it?
f-string, `.format()`, `%` formatting — which to use?
What are the 4 OOP principles in Python?
@classmethod vs @staticmethod vs instance method?
What is MRO? How does Python solve the diamond problem?
How does the `@property` decorator work?
How are abstract classes used in Python?
What is `@dataclass`? Benefits over regular classes?
What is `__slots__`? When should you use it?
What are the most important dunder (magic) methods to know?
What is the GIL? How does it affect threading and multiprocessing?
Threading vs Multiprocessing vs Asyncio — when to use each?
How do `async/await` and the event loop work?
`asyncio.gather` vs `asyncio.TaskGroup` — what's the difference?
What is a race condition? How to prevent it in asyncio?
What is FastAPI? How does it compare to Flask and Django?
How does Pydantic validation work in FastAPI?
How do you write custom middleware in FastAPI?
How do you implement JWT authentication in FastAPI?
Background Tasks vs Celery — when to use each?
How do you handle startup/shutdown events in FastAPI 0.95+?
What is the N+1 query problem? How to solve it with SQLAlchemy?
How do you set up SQLAlchemy 2.0 async with FastAPI?
How do you test FastAPI endpoints with pytest and TestClient?
How does pytest fixture `scope` work?
How do you use `pytest-mock` for mocking?
What is the cache-aside pattern? How to implement it with Redis in Python?
How do you manage app config with Pydantic Settings?
Why are type hints important in modern Python?
How do you implement WebSockets in FastAPI?
What are `*args` and `**kwargs`? When to use them?
What are `enumerate`, `zip`, `map`, `filter`? When to use them?
What is the walrus operator `:=` (Assignment Expression)? When is it useful?
Advanced type hints: `Optional`, `Union`, `TypeVar`, `Generic`, `Protocol`?
What are metaclasses in Python? When to use them?
Generators vs Iterators — how do they differ? `__iter__` and `__next__`?
Descriptor Protocol in Python — `__get__`, `__set__`, `__delete__`?
Async context managers and async generators — how to write them?
`ThreadPoolExecutor` and `ProcessPoolExecutor` with asyncio?
Pydantic v2 — what are the major changes from v1?
Async vs sync endpoints in FastAPI — when to use def vs async def?
pytest parametrize — how to write parameterized tests?
Mock vs MagicMock vs AsyncMock — what are the differences?
`@dataclass(slots=True)` — memory optimization in Python 3.10+?
What is the difference between `__new__` and `__init__` in Python?
How does Python pass arguments to functions?
What is the LEGB rule for name lookup? How do `global` and `nonlocal` differ?
What are list/dict/set comprehensions, and when should you use them?
What is `if __name__ == "__main__":` for?
How do `list.sort()` and `sorted()` differ?
What are pickling/unpickling, and why is unpickling untrusted data dangerous?
What problem do Exception Groups and `except*` (Python 3.11) solve?
How does `match`-case (structural pattern matching, 3.10) differ from a traditional `switch`?
What does `super()` actually do? What is cooperative multiple inheritance?
How do single vs double leading underscores in an attribute name differ? What is name mangling?
Why does a function declared as `def add(item, bucket=[])` keep data from previous calls?
What does `grid = [[0] * 3] * 2` followed by `grid[0][0] = 1` produce, and why?
How do `[x * x for x in data]` and `(x * x for x in data)` differ? When should a generator expression be preferred?
Why does `a = 256; b = 256; a is b` return `True` while the same code with `257` returns `False`?
How do you write a decorator that takes arguments (e.g. `@retry(times=3)`), and what problem does `functools.wraps` solve?
How is `yield from` different from writing `for item in sub: yield item`?
How do you write your own context manager, and what happens if `__exit__` returns `True`?
What happens when a class defines `__eq__` but not `__hash__` and you put an instance in a `set`?
`@dataclass`, `NamedTuple` or `pydantic.BaseModel` — which one should a real project use, and when?
Does Python check type hints at runtime? And what does `Optional[str]` mean?
Why do all functions in `fns = [lambda: i for i in range(3)]` return 2?
Has the GIL been removed? What does the free-threaded build (PEP 703) change for multi-threaded code?
An `async def` endpoint calls a heavy synchronous function (e.g. `requests.get`, image resizing). What does that do to the whole service, and how do you detect and fix it?
Reference counting frees an object as soon as its count hits zero, so why does Python still need the `gc` module? And when do you use `weakref`?
When does Python raise `TypeError: Cannot create a consistent method resolution order (MRO)`?
The same `multiprocessing` script runs fine on Linux but fails or spawns endlessly on macOS/Windows. Why?
One request needs to call 200 external APIs. What is wrong with a bare `asyncio.gather`? How do you bound concurrency?
Timeouts for outbound calls in async Python: how do `asyncio.timeout` and `wait_for` differ, and how do you handle `CancelledError`?