Python Interview Questions with Answers (2026)
Python interview questions for 2026: 18 real problems with concise answers and code on data types, decorators, the GIL, and generators interviewers test.
Python shows up in backend, data, automation and ML interviews, and the questions are rarely about syntax trivia — they probe whether you understand how Python actually behaves. Mutable defaults, the GIL, how is differs from ==: these separate people who use Python from people who understand it. Below are 18 real questions, ordered beginner to advanced, each with a concise answer or snippet you can rehearse out loud.
Beginner Python questions
1. What’s the difference between a list and a tuple?
A list is mutable (you can change it after creation) and uses []; a tuple is immutable and uses (). Tuples are slightly faster, can be dictionary keys, and signal “this shouldn’t change.” Use a tuple for fixed records, a list for collections you’ll modify.
2. How does is differ from ==?
== checks value equality; is checks identity (same object in memory). [1,2] == [1,2] is True, but [1,2] is [1,2] is False — two distinct objects. Only use is for singletons like None: write if x is None, never if x == None.
3. What are list comprehensions, and why use them? A concise way to build a list from an iterable:
squares = [n * n for n in range(10) if n % 2 == 0]
They’re faster than an explicit loop with .append() and more readable for simple transforms. Avoid them when the logic gets complex — readability wins.
4. What’s the difference between append() and extend()?
append(x) adds x as a single element; extend(iterable) adds each item. So [1,2].append([3,4]) gives [1,2,[3,4]], while [1,2].extend([3,4]) gives [1,2,3,4].
5. How do you handle exceptions in Python?
try:
result = risky()
except ValueError as e:
log(e)
except (KeyError, TypeError):
handle_other()
else:
use(result) # runs only if no exception
finally:
cleanup() # always runs
Catch specific exceptions, not a bare except:. The finally block runs whether or not an error occurred.
Intermediate Python questions
6. What is the difference between *args and **kwargs?
*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. They let a function accept a variable number of inputs:
def f(*args, **kwargs):
print(args, kwargs)
f(1, 2, x=3) # (1, 2) {'x': 3}
7. Explain the mutable default argument trap. A default argument is evaluated once, at function definition. So a mutable default is shared across calls:
def add(item, bucket=[]): # BUG
bucket.append(item)
return bucket
The fix:
def add(item, bucket=None):
if bucket is None:
bucket = []
bucket.append(item)
return bucket
8. What’s a dictionary comprehension? Give an example.
prices = {"a": 1, "b": 2}
doubled = {k: v * 2 for k, v in prices.items()}
9. How does Python manage memory? Python uses reference counting plus a cyclic garbage collector. Each object tracks how many references point to it; when that count hits zero, memory is freed. The generational GC handles reference cycles that counting alone can’t. Small integers and short strings are cached (interned) for reuse.
10. What’s the difference between @staticmethod and @classmethod?
A @classmethod receives the class as its first argument (cls) and can access/modify class state or build alternate constructors. A @staticmethod receives neither self nor cls — it’s just a function grouped under the class for organization.
11. Explain shallow vs deep copy.
A shallow copy (copy.copy() or list[:]) duplicates the outer object but shares nested references. A deep copy (copy.deepcopy()) recursively duplicates everything. So mutating a nested list in a shallow copy affects the original; in a deep copy it doesn’t.
Advanced Python questions
12. What is a decorator? Write one. A decorator is a function that wraps another function to extend its behavior:
import functools, time
def timed(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = fn(*args, **kwargs)
print(f"{fn.__name__} took {time.perf_counter()-start:.4f}s")
return result
return wrapper
@timed
def work():
...
functools.wraps preserves the original function’s name and docstring.
13. What’s a generator, and why use one?
A generator produces values lazily using yield, computing each on demand instead of building the whole sequence in memory:
def countdown(n):
while n > 0:
yield n
n -= 1
Use them for large or infinite streams — they keep memory flat. The trade-off: you can iterate them only once.
14. Explain the GIL. Why does it matter?
The Global Interpreter Lock allows only one thread to execute Python bytecode at a time. This means CPU-bound work doesn’t speed up with threads — use multiprocessing (separate processes) for that. Threads still help I/O-bound work (network, disk) because the GIL is released during blocking calls. (Note: Python 3.13+ ships an experimental free-threaded build, but the default interpreter still has the GIL.)
15. What’s the difference between __str__ and __repr__?
__str__ is the human-readable form (print(obj)); __repr__ is the unambiguous, developer-facing form, ideally one you could paste back to recreate the object. If you only define one, define __repr__ — it’s the fallback for both.
16. What are Python’s __slots__ and when would you use them?
__slots__ declares a fixed set of attributes, replacing the per-instance __dict__. This cuts memory use and speeds attribute access — valuable when you create millions of small objects. The cost: you lose dynamic attribute assignment.
17. How does async/await work at a high level?
async def defines a coroutine; await suspends it at I/O points, letting the event loop run other coroutines meanwhile. It gives concurrency on a single thread without the GIL problem, ideal for thousands of network calls. It is concurrency, not parallelism — CPU-bound work still blocks the loop.
18. What does if __name__ == "__main__": do?
When a file runs directly, its __name__ is "__main__"; when imported, it’s the module name. The guard lets code run on direct execution but stay silent on import — so a module can be both a library and a script.
How to stand out in a Python interview
Strong candidates explain why, not just what. When asked about the GIL, mention the threads-vs-processes consequence. When writing a comprehension, note when a loop would be clearer. Name trade-offs (generators save memory but iterate once; __slots__ saves memory but blocks dynamic attributes) — that reasoning is what gets scored.
Rehearse these out loud, because explaining a decorator is far harder than reading one. Practice full Python rounds with OnJob’s AI mock interviews and get a confidence score on your explanations, then create a free account to find matched backend and data roles. Pair this with our SQL interview questions and system design interview guide for a complete backend prep loop.
FAQ
What Python topics are most asked in interviews in 2026?
Data structures (list vs tuple vs dict vs set), comprehensions, exception handling, decorators, generators, the GIL and threads-vs-processes, mutable default arguments, and is vs ==. Data and ML roles add NumPy/pandas and async patterns.
Is the GIL still relevant in 2026? Yes. The default CPython interpreter still has the GIL, so CPU-bound work needs multiprocessing. Python 3.13+ offers an experimental free-threaded build, but knowing the classic GIL behavior and its threads-vs-processes consequence is still the expected interview answer.
How should I prepare for a Python coding round?
Practice writing clean code on a whiteboard or shared doc while talking through your reasoning, state assumptions before coding, name edge cases (empty input, None, duplicates), and rehearse explaining concepts like decorators and generators out loud — not just recognizing them.
Ready to put this into action?
Create your free OnJob profile and let AI match you to jobs you can actually win.
Create my free profileFree OnJob tools & guides
Related reading
50+ Interview Questions Asked for Freshers
Questions asked in an interview for freshers, with smart sample answers. Master common HR and technical rounds and walk in ready to get hired.
InterviewsReact Interview Questions (2026): Hooks, State & Performance
React interview questions for 2026 with concise answers on hooks, state, rendering, performance and the Server Components shift frontend rounds now test.
InterviewsSQL Interview Questions with Answers (2026)
SQL interview questions with answers for 2026: 15 real queries from beginner joins to advanced window functions that data and backend rounds test.
InterviewsSystem Design Interview Guide (2026)
System design interview guide for 2026: a repeatable framework, worked questions like URL shortener and news feed, plus caching and scaling answers.