Python Interview Questions and Answers
35 Python interview questions with answers and code: data types, mutability, functions, OOP, generators, decorators, the GIL, async, testing and coding exercises.
Key takeaways
- Python interviews focus on the data model: mutability, references, hashing and how built-in types behave.
- Expect generators, decorators and context managers at mid-level, and the GIL, async and memory at senior level.
- Many interviews include a coding task in Python, where idiomatic code (comprehensions,
collections,itertools) is noticed. - Know the complexity of built-in operations: list vs set lookups, dict operations, string concatenation.
Contents
Python interviews focus on how the language really works: the data model, functions, generators and concurrency, plus a coding task where idiomatic Python is expected. Below are 35 common questions grouped by topic and level, with concise answers and code.
What Python interviews cover
Editorial estimate for a backend or data role; data roles add pandas and NumPy questions.
- Core language and data model25%
- Coding exercise30%
- Functions, OOP and decorators15%
- Generators and iterators10%
- Concurrency and performance15%
- Testing and tooling5%
Complexity of common operations
| Operation | list | dict / set |
|---|---|---|
| Lookup by index / key | O(1) | O(1) average |
Membership test x in c | O(n) | O(1) average |
| Append / add | O(1) amortized | O(1) average |
| Insert or delete at the start | O(n) | — |
| Iterate | O(n) | O(n) |
For data roles, also see data scientist and data engineer questions; for algorithm practice, our coding interview tips.
Core language
1What is the difference between a list and a tuple?
JuniorLists are mutable, tuples are immutable. Because tuples can’t change, they are hashable when their items are, so they can be dictionary keys or set members, and they are slightly cheaper to create. Use tuples for fixed records and lists for collections that grow or change.
2Which built-in types are mutable and which are immutable?
JuniorImmutable: int, float, bool, str, tuple, frozenset, bytes. Mutable: list, dict, set, bytearray and most user-defined objects. Immutability matters for hashing and for understanding why changing an object inside a function affects the caller.
3What is the difference between is and ==?
Junior== compares values (it calls __eq__); is checks whether two names refer to the same object. Use is only for singletons such as None: if x is None:.
4How are arguments passed to functions in Python?
JuniorBy object reference (“call by sharing”). The function receives a reference to the same object. Mutating a mutable argument is visible to the caller; rebinding the parameter name is not.
5Why is a mutable default argument a bug?
JuniorDefault values are evaluated once, when the function is defined, so the same object is shared between calls:
def add(item, items=[]): # bug: one list for all calls
items.append(item)
return items
def add(item, items=None): # fix
items = [] if items is None else items
items.append(item)
return items
6Shallow copy vs deep copy?
JuniorA shallow copy (list(x), x.copy(), copy.copy) creates a new container that holds references to the same inner objects. A deep copy (copy.deepcopy) recursively copies the inner objects too, so changes to nested data don’t leak between copies.
7What are list, dict and set comprehensions?
JuniorConcise expressions for building collections:
squares = [x * x for x in nums if x > 0]
index = {user.id: user for user in users}
domains = {email.split("@")[1] for email in emails}
They are usually clearer and faster than equivalent loops with append.
8What makes an object hashable, and why does it matter?
MidA hashable object has a hash that never changes during its lifetime (__hash__) and can be compared with __eq__. Only hashable objects can be dict keys or set members. Objects that compare equal must have the same hash.
9What is the time complexity of common operations on lists, dicts and sets?
MidList: index access O(1), append amortized O(1), insert(0) and x in list O(n). Dict and set: lookup, insert and delete average O(1). That is why checking membership in a set is much faster than in a list for large data.
Functions and OOP
10What do *args and **kwargs mean?
Junior*args collects extra positional arguments into a tuple, **kwargs collects extra keyword arguments into a dict. They are also used in calls to unpack sequences and mappings: f(*values, **options).
11What is a closure?
MidA function that remembers variables from the scope where it was created, even after that scope has finished:
def counter():
count = 0
def inc():
nonlocal count
count += 1
return count
return inc
12What is a decorator? Write one.
MidA function that takes a function and returns a new one with extra behavior. functools.wraps keeps the original name and docstring:
import functools, time
def timed(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
start = time.perf_counter()
try:
return fn(*args, **kwargs)
finally:
print(f"{fn.__name__}: {time.perf_counter() - start:.3f}s")
return wrapper
13Instance, class and static methods: what’s the difference?
JuniorInstance methods receive self and work with one object. Class methods (@classmethod) receive cls and are often used as alternative constructors. Static methods (@staticmethod) receive neither and are plain functions grouped in the class namespace.
14What are dunder (magic) methods?
MidSpecial methods like __init__, __repr__, __eq__, __len__, __iter__ and __enter__ that let your objects work with built-in syntax and functions. Implementing __repr__ alone makes debugging much easier.
15How does inheritance and the MRO work in Python?
MidPython supports multiple inheritance. The method resolution order (MRO), computed with the C3 algorithm and visible in Class.__mro__, decides which parent’s method is used. super() follows the MRO, which makes cooperative multiple inheritance possible.
16When would you use dataclasses?
MidFor classes that mainly hold data. @dataclass generates __init__, __repr__ and __eq__, and supports defaults, ordering and immutability (frozen=True). For validation of external data, libraries like Pydantic are a common choice.
Get Python answer points in real time during your interview
Sottena listens to the interviewer, detects each question and shows short answer points in about a second. 150 free credits, no card required.
Iterators, generators and context managers
17What is the difference between an iterable and an iterator?
MidAn iterable can produce an iterator (__iter__), like a list. An iterator returns items one by one with __next__ and remembers its position; once exhausted, it stays exhausted. A for loop calls iter() on the iterable and then next() until StopIteration.
18What is a generator and why use one?
MidA function with yield that produces values lazily, one at a time, keeping its state between calls. Generators use constant memory for large or infinite sequences:
def read_lines(path):
with open(path) as f:
for line in f:
yield line.rstrip("\n")
19What is a context manager?
MidAn object used with with that sets something up and guarantees cleanup, even on exceptions (__enter__ / __exit__). Files, locks and database transactions are typical examples. contextlib.contextmanager lets you write one as a generator.
20Name useful tools from collections and itertools.
MidCounter for counting, defaultdict for grouping, deque for fast appends and pops at both ends, namedtuple for lightweight records. From itertools: groupby, chain, islice, product, combinations. Knowing them makes interview solutions shorter and clearer.
Concurrency and performance
21What is the GIL, and how does it affect performance?
SeniorIn CPython, the Global Interpreter Lock lets only one thread execute Python bytecode at a time. Threads still help for I/O-bound work, because the GIL is released while waiting. For CPU-bound work, use multiprocessing, native extensions (NumPy) or other approaches. Recent CPython versions offer an experimental free-threaded build without the GIL.
22Threads vs processes vs asyncio: when to use each?
Midasyncio: many concurrent I/O operations (network calls) in one thread. Threads: I/O-bound work with blocking libraries. Processes: CPU-bound work that needs multiple cores. concurrent.futures gives one interface for thread and process pools.
23How does async/await work?
Midasync def defines a coroutine; await pauses it until another awaitable finishes, letting the event loop run other tasks meanwhile. Run many requests concurrently with asyncio.gather:
results = await asyncio.gather(*(fetch(url) for url in urls))
Blocking calls (like time.sleep or a sync HTTP client) inside a coroutine block the whole loop.
24How does Python manage memory?
SeniorCPython uses reference counting, so most objects are freed as soon as their last reference disappears, plus a cyclic garbage collector for reference cycles. Memory leaks usually come from references kept in caches, globals or closures. tracemalloc helps find them.
25How do you find and fix a slow Python program?
SeniorProfile first with cProfile or py-spy to find the hot spots. Then improve the algorithm or data structure, avoid repeated work (caching with functools.lru_cache), move heavy numeric loops to NumPy, and batch I/O. Only after that consider multiprocessing or native extensions.
Errors, testing and tooling
26How does exception handling work?
Juniortry runs code, except handles specific exceptions, else runs if nothing failed, finally always runs. Catch the narrowest exception you can handle; a bare except: also hides bugs and KeyboardInterrupt.
27How do you test Python code?
MidMost teams use pytest: plain assert statements, fixtures for setup, parametrize for many inputs, and unittest.mock or monkeypatch to replace external dependencies. Keep unit tests fast and isolate network and database access.
28What are type hints, and are they enforced?
MidAnnotations like def f(x: int) -> str that document types. Python doesn’t enforce them at runtime; tools like mypy or Pyright check them statically. They improve editor support and catch bugs in larger codebases.
29How do you manage dependencies and environments?
JuniorUse a virtual environment per project (venv) and pin dependencies in a lock file. Common tools include pip with requirements files, Poetry and uv. This keeps projects isolated and builds reproducible.
Coding exercises
30Find the first non-repeating character in a string.
JuniorCount characters, then scan again in order. O(n) time:
from collections import Counter
def first_unique(s: str) -> str | None:
counts = Counter(s)
return next((ch for ch in s if counts[ch] == 1), None)
31Check whether two strings are anagrams.
JuniorCompare character counts: Counter(a) == Counter(b), O(n). Sorting both strings also works but is O(n log n).
32Return the k most frequent words.
Midfrom collections import Counter
def top_k(words: list[str], k: int) -> list[str]:
return [w for w, _ in Counter(words).most_common(k)]
most_common uses a heap when k is small. Mention ties and case normalization if the interviewer cares about them.
33Merge overlapping intervals.
MidSort by start, then extend or append:
def merge(intervals):
out = []
for start, end in sorted(intervals):
if out and start <= out[-1][1]:
out[-1][1] = max(out[-1][1], end)
else:
out.append([start, end])
return out
O(n log n) for the sort.
34Implement an LRU cache.
MidUse OrderedDict to track recency, giving O(1) get and put:
from collections import OrderedDict
class LRU:
def __init__(self, capacity):
self.cap, self.data = capacity, OrderedDict()
def get(self, key):
if key not in self.data:
return None
self.data.move_to_end(key)
return self.data[key]
def put(self, key, value):
self.data[key] = value
self.data.move_to_end(key)
if len(self.data) > self.cap:
self.data.popitem(last=False)
For memoizing functions, functools.lru_cache already exists.
35Process a 50 GB log file to count errors per hour.
SeniorStream it line by line with a generator so memory stays constant, parse only the fields you need, and aggregate into a Counter keyed by hour. If it’s too slow, split the file into byte ranges and process them in parallel with multiprocessing, then merge the counters. Mention that in production you might use a tool like Spark or a log pipeline instead.
How to prepare
- Master the data modelMutability, references, hashing and copying explain most tricky Python questions.
- Solve problems in idiomatic PythonUse comprehensions,
Counter,defaultdict,dequeandheapqinstead of reinventing them. - Know complexities of built-insBe ready to explain why a set lookup is O(1) and
list.insert(0)is O(n). - Prepare one concurrency storyWhen you used threads, processes or asyncio, and why.
- Write tests in the interviewA couple of quick
assertchecks after your solution shows good habits.
Get answer points in real time during your interview
Sottena listens to the interviewer, detects each question and shows short answer points in about a second. 150 free credits, no card required.