The Python interview landscape has evolved. It’s no longer enough to just know the difference between a list and a tuple. Modern interviews (heading into 2026) focus on memory management, concurrency, the modern type system, and the architectural shifts happening in the Python ecosystem (like the no-GIL build and uv).
Here is the definitive list of the Top 25 Python Interview Questions for 2026, categorized by domain, with deep-dive answers and code examples.
Section 1: Core Mechanics & Memory
1. What happens if you use a mutable object as a default argument?
One of the most classic Python gotchas. Default arguments are evaluated once at function definition time, not at call time. If you mutate it, the mutation persists across calls.
# ❌ BAD
def append_to(element, target=[]):
target.append(element)
return target
# ✅ GOOD
def append_to(element, target=None):
if target is None:
target = []
target.append(element)
return target
2. How does Python manage memory? (Explain Reference Counting and the GC)
CPython combines reference counting with a cyclic garbage collector; other Python implementations may differ. Collection timing and generation behavior depend on the Python version and build, including free-threaded builds. Consult the GC documentation for your deployed version rather than assuming all Python runtimes have identical memory management.
3. What is the difference between __new__ and __init__?
__new__is the allocator. It actually creates the object instance in memory. It is a static method that returns the new instance. Used primarily for subclassing immutable types (likestrortuple).__init__is the initializer. It configures the already created object. It returnsNone.
4. What are __slots__ and why would you use them?
By default, Python stores object attributes in a dynamic dictionary (__dict__). __slots__ explicitly declares a fixed set of attributes, preventing the creation of __dict__.
* Pros: Saves massive amounts of RAM (crucial for millions of objects) and slightly faster attribute access.
* Cons: You cannot dynamically add new attributes, and it complicates multiple inheritance.
5. Explain Deep vs. Shallow Copy.
- Shallow Copy: Creates a new object, but populates it with references to the child objects found in the original. (e.g.,
copy.copy()orlist(original_list)). Modifying a nested mutable object affects both. - Deep Copy: Recursively copies the original object and all objects contained within it. (e.g.,
copy.deepcopy()). They are completely independent.
6. How do Descriptors work?
Descriptors are objects that implement any of __get__, __set__, or __delete__. They allow you to customize attribute lookup. property, classmethod, and staticmethod are all built using descriptors. They power the ORM fields in SQLAlchemy and Django.
# Descriptor demonstration only: real passwords must be hashed by an auth system.
class VerifiedPassword:
def __set_name__(self, owner, name):
self.name = name
def __get__(self, obj, objtype=None):
if obj is None:
return self
return obj.__dict__[self.name]
def __set__(self, obj, value):
if len(value) < 8:
raise ValueError("Password too short")
obj.__dict__[self.name] = value
Section 2: OOP & Metaprogramming
7. Explain Method Resolution Order (MRO) in multiple inheritance.
When a class inherits from multiple parents, Python uses the C3 Linearization algorithm to determine the order in which base classes are searched for a method. It ensures that a child class is always checked before its parents, and the order of parents is preserved. You can view it via ClassName.mro().
graph TD
A[Class D] --> B[Class B]
A --> C[Class C]
B --> D[Class A]
C --> D
Search order: D -> B -> C -> A
8. What is a Metaclass and what is a practical use case?
A metaclass is the "class of a class." Just as a class defines how an instance behaves, a metaclass defines how a class behaves. Python uses type as the default metaclass.
* Use Case: Enforcing coding standards, registering classes automatically (like a Plugin Registry), or preventing class creation if abstract methods aren't implemented (similar to abc.ABCMeta).
9. How do @classmethod, @staticmethod, and instance methods differ?
- Instance Method: Receives
self(the instance) as the first arg. Can read/write instance state. - Class Method: Receives
cls(the class) as the first arg. Used for factory methods (alternative constructors). - Static Method: Receives neither
selfnorcls. Just a namespace for a utility function logically related to the class.
10. What are Data Classes?
Introduced in PEP 557 (Python 3.7), @dataclass auto-generates __init__, __repr__, and __eq__ based on type hints. It drastically reduces boilerplate. Use frozen=True to prevent ordinary attribute reassignment; mutable objects stored in fields can still change.
11. Explain the __call__ method.
If a class implements __call__, its instances can be called like functions. This is often used for stateful function-like objects, or for creating class-based decorators (where the class takes the function in __init__ and wraps it in __call__).
Section 3: Concurrency & Asyncio
12. What is the GIL (Global Interpreter Lock)?
In a GIL-enabled CPython build, the global interpreter lock serializes Python bytecode execution. Optional free-threaded builds have different behavior; the GIL is not a universal property of Python. * I/O Bound: Multithreading works fine; the GIL is released during I/O operations (network, file). * CPU Bound: Pure Python threads generally do not run bytecode in parallel with the GIL enabled. Consider processes, native code that releases the GIL, or a compatible free-threaded build.
13. Python 3.13 introduced a "Free-Threaded" build (PEP 703). What does this mean?
CPython 3.13 introduced an optional free-threaded build. It can run Python threads in parallel, but synchronization is still necessary and speedups depend on the workload. Some extension modules can re-enable the GIL. See the free-threading guide and check the actual runtime and dependencies.
14. Multiprocessing vs. Multithreading vs. Asyncio?
- Multithreading: Good for I/O-bound tasks. Threads share memory, but subject to the GIL.
- Multiprocessing: Good for CPU-bound tasks. Each process has its own memory space and Python interpreter (bypasses GIL). High memory overhead.
- Asyncio: Single-threaded, concurrent code using an event loop. Best for massive I/O-bound tasks (thousands of simultaneous network connections) with the lowest overhead.
15. How does the Asyncio Event Loop work?
The event loop runs in a single thread. It keeps track of coroutines and tasks. An await can suspend a coroutine when the awaited operation is not ready; not every await actually yields control, and blocking synchronous calls still block the event-loop thread. The loop then executes other tasks. When the I/O is ready, the loop resumes the paused coroutine.
16. What are Async Generators?
Combining async def and yield. They allow you to asynchronously stream data.
async def fetch_stream():
async for item in database_cursor:
yield item
async def main():
async for item in fetch_stream():
print(item)
Section 4: Modern Python & The Type System
17. What is Duck Typing vs. Structural Subtyping (Protocols)?
- Duck Typing: "If it walks like a duck and quacks like a duck, it's a duck." Python doesn't care about the actual type, only if the method exists at runtime.
- Protocols (PEP 544): Static typing's version of duck typing. You define a
Protocolclass with methods. Any class that implements those methods satisfies the Protocol, without explicitly inheriting from it.
18. Explain TypeVar and Generics.
Generics allow you to write functions or classes that work with any type, while preserving type information.
from typing import TypeVar, Generic
T = TypeVar('T')
def first(items: list[T]) -> T:
return items[0]
# The type checker knows first([1,2]) returns int,
# and first(["a"]) returns str
19. What is ParamSpec?
Introduced to type decorators properly. It captures the parameter signature of a function, allowing you to write decorators that accept *args, **kwargs without losing the original function's type hints.
20. Explain Structural Pattern Matching (match/case).
Introduced in Python 3.10, it is much more powerful than C-style switch statements. It matches against structure, not just values.
def handle_command(command):
match command.split():
case ["quit"]:
exit()
case ["go", direction]:
move(direction)
case ["pick", "up", item]:
add_to_inventory(item)
case _:
print("Unknown command")
21. pydantic vs dataclasses?
- Dataclasses: Standard library, pure boilerplate reduction, no validation.
- Pydantic: Third-party (now foundational to FastAPI). Validates data at runtime using type hints, automatically parsing strings to ints/dates, and raising
ValidationErrorif data is malformed. Essential for API boundaries.
Section 5: Architecture & Ecosystem
22. How do you manage dependencies in 2026? (uv vs pip)
While pip and requirements.txt are classic, modern Python relies on pyproject.toml. uv (by Astral, makers of Ruff) is rapidly becoming the standard. It provides project, environment, and package-management workflows, but is not a universal drop-in replacement for every existing tool. Review migration differences and measure performance on your dependency set.
23. What is the difference between WSGI and ASGI?
- WSGI: Synchronous web server interface (e.g., Gunicorn + Flask/Django). Handles one request per thread.
- ASGI: Asynchronous Server Gateway Interface (e.g., Uvicorn + FastAPI/Django). Supports
async/await, WebSockets, and long-polling HTTP connections.
24. How do you profile a Python application?
cProfile: Built-in.python -m cProfile -s time my_script.pyto see where time is spent.py-spy: A sampling profiler that runs without restarting the program or modifying code.memray: Modern memory profiler (developed by Bloomberg) that tracks memory allocations in Python code, C extensions, and the OS.
25. When should you use C-Extensions (or Cython/Rust)?
When Python is too slow for CPU-bound tasks and multiprocessing overhead is too high. Tools like Cython (Python-like syntax compiling to C) or PyO3 (writing native Python modules in Rust) allow you to rewrite the critical 5% of your codebase in a compiled language, accelerating measured bottlenecks. Native extensions do not automatically release the GIL; that requires appropriate implementation and thread-safety.

