RURU

Top 30 Python Interview Questions and Answers (2026)

· 7 min read

These are the Python questions that come up most in interviews for backend, data and full-stack roles. The answers are short on purpose: interviewers want a clear explanation first, then an example. Practise saying each answer aloud in under a minute.

Core language

1. What are Python's main built-in data types?

Numbers (int, float, complex), bool, str, list, tuple, set, frozenset, dict, bytes and None. Lists, dicts, sets and bytearrays are mutable; ints, floats, strings, tuples and frozensets are immutable.

2. What's the difference between a list and a tuple?

Lists are mutable and usually hold items of the same kind that change over time. Tuples are immutable, slightly lighter, can be used as dictionary keys (if their contents are hashable), and often represent fixed records, like (latitude, longitude).

3. What's the difference between is and ==?

== compares values; is checks whether two names point to the same object. Use is for None (x is None) and == for everything else.

4. How do *args and **kwargs work?

*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. They're used for flexible function signatures and for passing arguments through wrappers and decorators.

5. What's wrong with a mutable default argument?

Default values are evaluated once, when the function is defined. A default list or dict is shared across calls, so changes leak between them. Use None as the default and create the list inside the function.

6. Explain list, dict and set comprehensions.

Compact expressions that build a collection from an iterable, optionally with a filter: squares = [n * n for n in nums if n > 0]. They're usually clearer and faster than the equivalent loop with append.

7. What's the difference between a shallow and a deep copy?

A shallow copy (copy.copy, list slicing) creates a new outer object but shares the inner objects. A deep copy (copy.deepcopy) recursively copies everything, so changes to nested objects don't affect the original.

8. How does Python handle scope? What's LEGB?

Names are looked up in order: Local, Enclosing function, Global (module), Built-in. Use "global" or "nonlocal" to assign to an outer name from inside a function.

Memory and internals

9. How does Python manage memory?

CPython uses reference counting: each object tracks how many references point to it and is freed when the count reaches zero. A cyclic garbage collector (the gc module) finds and frees groups of objects that reference each other but are no longer reachable.

10. What is the GIL?

The Global Interpreter Lock in CPython lets only one thread execute Python bytecode at a time. Threads still help with I/O-bound work (the lock is released while waiting), but CPU-bound work needs multiprocessing, native extensions that release the GIL, or other approaches. Python 3.13 added an optional free-threaded build without the GIL, and 3.14 made it officially supported, but the standard build still has the GIL.

11. Threads, processes or asyncio: when do you use each?

asyncio for many concurrent I/O tasks in one thread (thousands of network calls). Threads for I/O-bound work with blocking libraries. Processes (multiprocessing, ProcessPoolExecutor) for CPU-bound work that needs multiple cores.

12. What are __slots__?

Declaring __slots__ in a class replaces the per-instance __dict__ with fixed attribute slots. It saves memory when you create many instances and prevents adding new attributes by accident.

Functions, decorators and generators

13. What is a decorator?

A function that takes a function and returns a new one that adds behaviour: logging, caching, authentication, timing. The @decorator syntax is shorthand for func = decorator(func). Use functools.wraps inside it to keep the original name and docstring.

14. How do you write a decorator that takes arguments?

Add one more layer: an outer function takes the arguments and returns the actual decorator, which returns the wrapper. For example, @retry(times=3) calls retry(times=3) first, and its result decorates the function.

15. What is a generator, and why use one?

A function that uses yield to produce values one at a time, pausing between them. Generators are lazy: they don't build the whole result in memory, which makes them ideal for large files, streams and pipelines.

16. What's the difference between an iterator and an iterable?

An iterable can be looped over: it has __iter__ (lists, dicts, files). An iterator is the object that produces the values: it has __next__ and remembers where it is. iter(iterable) returns an iterator; a generator is an iterator.

17. What does yield from do?

It delegates to a sub-generator or iterable, yielding all its values (and passing sent values and exceptions through). It keeps nested generators simple.

18. What are lambda functions, and when shouldn't you use them?

Small anonymous single-expression functions, handy as sort keys: sorted(users, key=lambda u: u.age). Don't use them for anything complex or reused. A named function is easier to read and test.

19. What are context managers?

Objects used with "with" that set something up and reliably clean it up (files, locks, database transactions), via __enter__ and __exit__. contextlib.contextmanager lets you write one as a generator.

Object-oriented Python

20. Explain @staticmethod, @classmethod and instance methods.

Instance methods receive the instance (self). Class methods receive the class (cls) and are often used as alternative constructors. Static methods receive neither; they're plain functions namespaced inside the class.

21. What is the MRO?

The Method Resolution Order: the order Python searches classes for a method in multiple inheritance, computed with the C3 linearisation. You can see it with ClassName.__mro__. super() follows the MRO, not just the direct parent.

22. What are dataclasses?

The @dataclass decorator generates __init__, __repr__, __eq__ and optionally ordering and immutability (frozen=True) from type-annotated fields. They remove boilerplate from classes that mainly hold data.

23. What are dunder (magic) methods?

Special methods like __len__, __eq__, __hash__, __repr__ and __add__ that let your objects work with built-in syntax and functions. If you define __eq__, define __hash__ too (or the object becomes unhashable).

Async Python

24. How does async/await work?

An "async def" function returns a coroutine. "await" pauses it until the awaited operation finishes, letting the event loop run other coroutines meanwhile. Concurrency comes from overlapping waits, not from parallel execution.

25. What happens if you call blocking code inside async code?

It blocks the whole event loop: every other task waits. Use async libraries (httpx, asyncpg), or move the blocking call to a thread with asyncio.to_thread or run_in_executor.

26. How do you run several coroutines concurrently?

asyncio.gather(...) or, in Python 3.11+, asyncio.TaskGroup, which also cancels the remaining tasks if one fails. Use a Semaphore to limit how many run at once.

Django and FastAPI

27. What is the N+1 query problem in Django, and how do you fix it?

Looping over objects and touching a related field triggers one query per object. Fix it with select_related (follows foreign keys with a JOIN) and prefetch_related (separate query for many-to-many and reverse relations).

28. How does Django middleware work?

Middleware wraps every request and response, in the order listed in settings. Each one can modify the request before the view and the response after it. Common uses: authentication, security headers, logging.

29. Why choose FastAPI?

It's built for async, uses type hints and Pydantic for request validation and serialisation, and generates OpenAPI documentation automatically. It suits APIs and microservices; Django suits full applications with an admin, ORM and auth built in.

30. How do you test Python code?

pytest with fixtures and parametrised tests; unittest.mock to replace external calls; separate unit tests from integration tests that hit a real database; and coverage to find untested code. For APIs, use the framework's test client.

How to use this list

Don't memorise answers word for word. For each question, be ready to explain it simply, give an example, and mention a real situation where it mattered in your work. Interviewers often follow up with "Where have you used this?".

Python rounds usually sit next to a coding round and, for senior roles, a system design interview. Make sure your software engineer resume highlights the Python work you want to talk about.

More guides

All guides