Python Interview Questions and Answers for Freshers
Python interviews test whether you understand the language's model — how names bind to objects, what mutability implies, how iteration is lazy — rather than syntax. These are the questions that come up, with the traps interviewers use to check.
- 25questions
- 9basic
- 12intermediate
- 4advanced
Data types and mutability
6 questionsWhere most Python follow-ups originate.
What is the difference between a set and a dictionary?
What is the mutable default argument trap?
None and create the object inside the function.def add(item, basket=[]): # wrong: one list, shared forever
basket.append(item)
return basket
add('a') # ['a']
add('b') # ['a', 'b'] <- surprise
def add(item, basket=None): # correct
basket = [] if basket is None else basket
basket.append(item)
return basketWhat is the difference between `is` and `==`?
== compares values; is compares identity — whether both names refer to the same object. Small integers and short strings are cached, so is appears to work on them and then fails on larger values. Use is only for singletons: x is None.What is the difference between a shallow and a deep copy?
copy.copy() duplicates the outer object but shares the nested ones, so mutating a nested list is visible through both. copy.deepcopy() duplicates recursively. Slicing (lst[:]) is a shallow copy too — a frequent source of surprise with lists of lists.How do Python's *args and **kwargs work?
*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. At a call site the same symbols do the reverse — they unpack a sequence or a mapping into arguments. They are what let a decorator wrap a function of any signature.Functions, decorators and generators
5 questionsThe intermediate round — asked to see whether you write Python or write Java in Python.
What is a decorator?
@ syntax is shorthand for reassigning the name to the wrapped version.import functools, time
def timed(fn):
@functools.wraps(fn) # keeps the original name and docstring
def wrapper(*args, **kwargs):
start = time.perf_counter()
try:
return fn(*args, **kwargs)
finally:
print(f"{fn.__name__} took {time.perf_counter() - start:.3f}s")
return wrapper
@timed
def slow(): ...functools.wraps? Without it the wrapper replaces the function's name, docstring and signature, which breaks introspection and confuses every debugging session afterwards.What is a generator, and why use one?
yield instead of return, producing values one at a time and suspending in between. It holds one item in memory rather than the whole sequence, so it can process a file larger than RAM, or an infinite stream. The cost is that it can only be consumed once.def read_lines(path):
with open(path) as f:
for line in f: # lazy: one line at a time
yield line.rstrip()
# memory stays flat no matter how large the file is
count = sum(1 for line in read_lines('huge.log') if 'ERROR' in line)What is the difference between a list comprehension and a generator expression?
sum, any, max — the generator is the better choice, because the list you build is thrown away anyway.What is the difference between an iterator and an iterable?
__iter__. An iterator produces the next value: it implements __next__ and raises StopIteration when exhausted. A list is iterable but is not an iterator, which is why you can loop over it repeatedly; a generator is its own iterator, which is why you cannot.What does the `with` statement do?
__enter__ runs on entry and __exit__ on exit, including when the body raises. It is how files get closed and locks released without a try/finally at every call site.Runtime, OOP and performance
5 questionsThe questions that separate scripting familiarity from understanding.
What is the GIL, and what does it mean for you?
multiprocessing, which runs separate interpreters.How does Python manage memory?
What is the difference between @staticmethod and @classmethod?
@classmethod receives the class as its first argument, so it can construct instances of the actual subclass — which is what makes it right for alternative constructors like from_json. A @staticmethod receives nothing implicit; it is a plain function that lives in the class for organisation.What is `self`, and why must it be written explicitly?
Class.method(instance).How would you speed up a slow Python loop?
cProfile or timeit, never a guess. Then, in order of return: use the right data structure (a set for membership turns an O(n²) scan into O(n)); move the work into built-ins and comprehensions, which run in C; use a library that vectorises it, such as NumPy; and only then reach for multiprocessing or a compiled extension.Everyday Python
9 questionsThe questions that check you have written real Python, not just studied it.
How do you merge two dictionaries?
a | b from Python 3.9, or {**a, **b} before that. In both, keys in b win. a.update(b) does it in place and returns None — assigning its result is a common slip.What is an f-string, and why prefer it?
f"{name} scored {score:.2f}". It is faster than % and .format(), reads in the order it prints, and supports format specifiers and, since 3.8, f"{value=}" for debugging, which prints both the expression and its value.How do you sort a list of dictionaries by a field?
sorted(items, key=lambda d: d['score'], reverse=True), or operator.itemgetter('score') which is faster. Python's sort is stable, so sorting twice — by the secondary key first, then the primary — gives a correct multi-level sort.from operator import itemgetter
rows.sort(key=itemgetter('name')) # secondary key first
rows.sort(key=itemgetter('score'), reverse=True) # then primary - stableWhen would you use a deque instead of a list?
list.pop(0) is O(n) because every remaining element shifts; collections.deque gives O(1) at both ends. It is the right structure for a queue, a sliding window, or a bounded history with maxlen.What is the difference between a module and a package?
.py file. A package is a directory of modules, historically marked by __init__.py. Both are imported the same way; a package just adds a namespace level.What is a virtual environment, and why does every project need one?
python -m venv .venv creates one.How do you handle exceptions well in Python?
except: — that swallows KeyboardInterrupt and hides real bugs. Keep the try block to the line that can actually fail. Use else for the code that runs only when nothing was raised, and finally for cleanup. When re-raising with context, raise NewError(...) from e preserves the original traceback.What are type hints, and do they do anything at runtime?
How would you read a very large file without running out of memory?
for line in f:. Combine it with a generator pipeline so filtering and transforming stay lazy too. f.read() and f.readlines() both pull the entire file into memory and are the wrong answer here.Reading answers is not the same as giving them
Most candidates know the material and still stumble when asked out loud. Take a Python mock interview where the interviewer follows up on what you actually say.
Other interview question sets
Java
Java interview questions with real answers
JavaScript
JavaScript interview questions with real answers
SQL
SQL interview questions with real answers and queries
React
React interview questions with real answers
Spring Boot
Spring Boot interview questions with real answers
DSA
DSA interview questions with real answers
System Design
System design interview questions with real answers