Python interview questions covering OOP, data structures, decorators, generators, and Pythonic best practices.
8 Questions Detailed Answers
1What is the difference between list, tuple, set, and dictionary?
Easy
View Answer
List: ordered, mutable, allows duplicates `[1,2,3]`. Tuple: ordered, immutable `(1,2,3)`. Set: unordered, mutable, no duplicates `{1,2,3}`. Dictionary: key-value pairs, ordered (3.7+) `{"a":1}`. Use tuples for fixed data, sets for uniqueness, dicts for lookups.
2Explain decorators in Python.
Medium
View Answer
Decorators modify function behavior without changing its code. They're functions that take a function and return a modified function. `def timer(func): def wrapper(*args): start = time.time(); result = func(*args); print(f"Took {time.time()-start}s"); return result; return wrapper`. Use `@timer` above any function to time it.
3What are generators? How are they different from lists?
Medium
View Answer
Generators produce values lazily using `yield`, consuming O(1) memory vs O(n) for lists. `def fib(): a, b = 0, 1; while True: yield a; a, b = b, a+b`. Use `next(gen)` or `for x in gen`. Perfect for large datasets or infinite sequences.
4What is the GIL (Global Interpreter Lock)?
Hard
View Answer
The GIL is a mutex in CPython that allows only one thread to execute Python bytecode at a time. This means CPU-bound tasks don't benefit from multithreading. Solutions: use `multiprocessing` for CPU-bound tasks, `asyncio` or threading for I/O-bound tasks.
5Explain list comprehension vs map/filter.
Easy
View Answer
List comprehension: `[x**2 for x in range(10) if x%2==0]` — More Pythonic, readable. map/filter: `list(map(lambda x: x**2, filter(lambda x: x%2==0, range(10))))` — Functional style. List comprehensions are generally preferred in Python for readability.
6What is the difference between deepcopy and shallow copy?
Medium
View Answer
Shallow copy (`copy.copy()`) creates a new object but references the same nested objects. Deep copy (`copy.deepcopy()`) creates completely independent copies of all nested objects. `a = [[1,2]]; b = copy.copy(a); a[0].append(3)` — b is also affected. With deepcopy, b remains unchanged.
7What are *args and **kwargs?
Easy
View Answer
`*args` collects extra positional arguments as a tuple. `**kwargs` collects extra keyword arguments as a dict. `def func(*args, **kwargs): print(args, kwargs)`. `func(1, 2, name="test")` → `(1, 2) {"name": "test"}`. Used for flexible function signatures.
8Explain Python's MRO (Method Resolution Order).
Hard
View Answer
MRO determines which method to call in multiple inheritance. Python uses C3 linearization. Check with `ClassName.__mro__`. For `class D(B, C)` where B and C both inherit from A: D → B → C → A. This avoids the diamond problem.