10 More Python Common Interview Questions and Answers (Part 2). Continuing our Python interview prep series, here are 10 more essential Python interview questions—ranging from object-oriented internals to advanced scoping and memory concepts—complete with clean code examples.
11. What is "Monkey Patching" in Python?
Monkey patching refers to dynamically modifying or extending a class or module at runtime, without altering its original source code. Because Python is a dynamic language, classes and functions are objects that can be reassigned on the fly.
While it can be useful for debugging, testing (e.g., mocking out network calls), or quick hotfixes, overuse can make code hard to trace and lead to unexpected bugs.
# Original class
class Calculator:
def add(self, a, b):
return a + b
# Monkey-patched function
def multiply(self, a, b):
return a * b
# Patching the class at runtime
Calculator.multiply = multiply
calc = Calculator()
print(calc.multiply(3, 4)) # 12 (dynamically added method)
12. What is the difference between isinstance() and type()?
type(obj)returns the exact type of the object. It does not take inheritance into account.isinstance(obj, classinfo)checks if an object is an instance of that class or any of its subclasses.
For object-oriented programming and type checking, isinstance() is strongly preferred because it supports polymorphism and inheritance.
class Animal:
pass
class Dog(Animal):
pass
dog = Dog()
print(type(dog) is Animal) # False
print(isinstance(dog, Animal)) # True (accounts for inheritance)
13. How do Python dictionaries work under the hood?
Python dictionaries are implemented using hash tables.
- Keys must be hashable (meaning their value/hash cannot change during their lifetime, so they must be immutable like strings, numbers, or tuples).
- When you store a key-value pair, Python passes the key through a hash function to compute an integer index, which determines where the value is stored in memory.
- Because lookups use this hash-based indexing rather than scanning a list sequentially, dictionary lookups, insertions, and deletions generally operate in $O(1)$ average time complexity.
14. What is Method Resolution Order (MRO) and C3 Linearization?
Method Resolution Order (MRO) is the order in which Python looks for a method or attribute in a hierarchy of classes, especially when multiple inheritance is involved.
Python uses the C3 Linearization algorithm to determine this order, preventing ambiguity issues like the "Diamond Problem." You can inspect a class's MRO using the __mro__ attribute or .mro() method.
class A:
def process(self):
print("A process")
class B(A):
pass
class C(A):
def process(self):
print("C process")
class D(B, C):
pass
print(D.__mro__)
# (<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>)
15. Explain the difference between __init__, __new__, and __call__.
__new__(cls): The actual constructor. It is responsible for creating and returning a new instance of the class (usually by callingsuper().__new__(cls)). It is a static method.__init__(self): The initializer. It takes the newly created instance (self) and sets up its initial state/attributes. It does not return anything.__call__(self): Allows an instance of a class to be called like a regular function.
class Multiplier:
def __init__(self, factor):
self.factor = factor
def __call__(self, x):
return x * self.factor
double = Multiplier(2)
print(double(5)) # 10 (instance called like a function)
16. What is the difference between an iterable and an iterator?
- Iterable: Any object that you can loop over (e.g., lists, strings, dictionaries). It implements the
__iter__()method, which returns an iterator. - Iterator: An object that statefully produces the next value when
next()is called on it. It implements both__iter__()(returning itself) and__next__().
Every iterator is an iterable, but not every iterable is an iterator (for instance, a list is an iterable, but calling next([1, 2, 3]) will raise a TypeError until you turn it into an iterator using iter()).
17. What is a lambda function and what are its limitations?
A lambda function is a small, anonymous (nameless) function defined using the lambda keyword.
- Limitation: They can only contain a single expression and cannot include statements like
return,pass,assert, or assignments (=). They are typically used for short, throwaway operations (like custom sorting keys).
# Sorting a list of tuples by the second element
pairs = [(1, 5), (3, 2), (2, 8)]
pairs.sort(key=lambda x: x[1])
print(pairs) # [(3, 2), (1, 5), (2, 8)]
18. What is the @property decorator used for?
The @property decorator allows you to define a method that can be accessed like a regular attribute. It lets you add getter, setter, and deleter logic to an attribute without changing the public interface of your class, maintaining encapsulation.
class Person:
def __init__(self, name):
self._name = name
@property
def name(self):
return self._name
@name.setter
def name(self, value):
if not value:
raise ValueError("Name cannot be empty")
self._name = value
p = Person("Alice")
print(p.name) # Accesses it like an attribute, calls getter
p.name = "Bob" # Calls setter
19. How does Python exception handling work (try, except, else, finally)?
Python uses a structured try-except block to gracefully handle runtime errors:
try: Code block that might raise an exception.except: Catches and handles specific exceptions.else: Executes only if thetryblock ran successfully without raising any exceptions.finally: Executes always, regardless of whether an exception occurred or was handled (useful for cleanup like closing files or database connections).
try:
result = 10 / 2
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print("Execution successful:", result)
finally:
print("Cleaning up resources...")
20. What is the LEGB rule for Python scopes?
When Python looks up a variable name, it searches through scopes in a specific order known as the LEGB rule:
- L - Local: Names assigned inside a function or lambda.
- E - Enclosing: Names in the local scope of any enclosing functions (closures/nested functions).
- G - Global: Names assigned at the top level of a module script or declared
globalinside a function. - B - Built-in: Preassigned names in Python's built-in namespace (e.g.,
print,len,range).
If a variable isn't found in any of these four levels, Python raises a NameError.