Complete Python Progressive Master Question Bank
75 progressive Python interview questions covering foundations, data structures, object-oriented concepts, memory mechanics, decorators, concurrency, and advanced language internals.
Q1: What is Python and how does its execution flow differ from compiled languages?
Python is a high-level, dynamically typed, interpreted programming language. Source code (.py) is first compiled into intermediate bytecode (.pyc). The Python Virtual Machine (PVM) then interprets this bytecode line-by-line into machine code at runtime.
import dis
def add(a, b):
return a + b
dis.dis(add) # Disassembles bytecode instructionsThe dis module exposes the raw PVM bytecode instructions produced for Python functions.
Compilation to Bytecode (
.pyc) occurs automatically prior to PVM interpretation.Dynamic typing resolves variable types at runtime rather than compile time.
What component in Python directly executes bytecode (.pyc) files?
Q2: What are the key operational differences between Lists and Tuples?
Lists are mutable sequence structures ([]), allocating extra memory over-allocation for dynamic resizing. Tuples are immutable sequence structures (()), occupying lower fixed memory footprint, faster allocation speeds, and supporting usage as dictionary keys.
Lists = Mutable, higher memory overhead.
Tuples = Immutable, lower memory, hashable (can be dict keys).
Can a tuple containing a list element be used as a key inside a Python Dictionary?
Q3: How do Dictionaries and Sets achieve O(1) average lookup times?
Python dictionaries and sets are backed by Hash Tables. Key hashes are computed via hash(key). In Python 3.6+, dictionaries use a compact array layout (an index array + a dense entries array), preserving insertion order while maintaining $O(1)$ key lookup and deletion.
Uses hash tables for $O(1)$ average lookups.
Python 3.6+ dicts preserve insertion order while reducing memory by ~20-25%.
What is the average time complexity for searching an element in a Python Set?
Q4: Why are mutable default arguments (e.g. def fn(arg=[])) considered dangerous?
Default argument values are evaluated once when the function definition is executed at module import time, NOT on each function invocation. Passing mutable default arguments ([] or {}) causes all subsequent calls to mutate the exact same shared object instance.
# ❌ DANGEROUS: Shared list reference across invocations
def append_to(element, target=[]):
target.append(element)
return target
# ✅ SAFE PATTERN: Re-instantiate mutable inside call
def safe_append(element, target=None):
if target is None:
target = []
target.append(element)
return targetRe-assigning target = [] inside function scope creates fresh list allocations per call.
Default parameter objects bind at function definition time.
Use
Noneas default placeholder and assign new mutables inside the body.
What is returned by append_to(1) followed by append_to(2) using the dangerous pattern above?
Q5: What is the difference between the 'is' operator and the '==' operator?
==Operator: Checks value equality (invokes__eq__()).isOperator: Checks object identity (verifies if two variables reference the exact same memory address usingid(a) == id(b)).
==tests equivalence of values.istests memory address identity.
What does [1, 2] == [1, 2] and [1, 2] is [1, 2] evaluate to?
Q6: What is the difference between copy.copy() and copy.deepcopy()?
- Shallow Copy (
copy.copy()): Creates a new container object, but populates it with references to child objects inside the original. - Deep Copy (
copy.deepcopy()): Recursively duplicates the container AND all nested child objects, constructing completely independent object graphs.
Shallow copy duplicates top-level container only.
Deep copy duplicates container and all nested child object references recursively.
If you modify a nested list inside a shallow copied object, does the original object's nested list update?
Q7: How do *args and **kwargs function in Python signatures?
*args: Captures variable positional parameters as a Tuple.**kwargs: Captures variable keyword parameters as a Dictionary. Allow passing arbitrary parameter lists to functions or forwarding arguments in wrapper functions.
def logger(func):
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__} with {args} and {kwargs}")
return func(*args, **kwargs) # Unpacks parameters seamlessly
return wrapper*args and **kwargs capture and forward arbitrary parameters to the target function.
*argscollects positional arguments into a tuple.**kwargscollects keyword arguments into a dictionary.
What type of data structure is *args stored as inside function scope?
Q8: What are List Comprehensions versus Generator Expressions?
- List Comprehension (
[x for x in data]): Evaluates the entire sequence eagerly, building a full list in heap memory. - Generator Expression (
(x for x in data)): Evaluates elements lazily on-demand, returning an iterator with minimal $O(1)$ memory footprint.
List Comprehension = Eager evaluation ($O(N)$ memory). Generator Expression = Lazy iteration ($O(1)$ memory).
Which construct should be preferred when streaming 10 GB of log data line-by-line?
Q9: What are Lambda functions and what limitations do they enforce?
Lambda functions are small, anonymous single-line functions created via lambda params: expression. They automatically return expression results and are restricted to a single expression (no statements, assignments, or multiline loops allowed).
Single-expression inline functions.
Useful for short callbacks in
map(),filter(), orsorted(key=...).
Can a lambda function contain explicit return statements or assignment operations in Python?
Q10: What is the LEGB Rule for Python scope resolution?
Python resolves variable names in strict sequential order:
- L (Local): Inside active function/lambda body.
- E (Enclosing / Nonlocal): In enclosing nested function scopes.
- G (Global): At module top-level.
- B (Built-in): Preloaded Python built-in names (
len,range).
Scope resolution order: Local -> Enclosing -> Global -> Built-in.
Use
globalornonlocalkeywords to rebind variables in outer scopes.
Which keyword must be used inside a nested inner function to rebind a variable declared in its parent outer function scope?
Q11: How does Python pass arguments to functions (Pass-by-Object-Reference)?
Python uses Pass-by-Object-Reference (or Pass-by-Assignment). Variable names are bindings pointing to objects in memory:
- Mutating a mutable object (e.g.
list.append()) alters the object in-place, affecting callers. - Reassigning the parameter variable name (
arg = new_value) breaks the binding, leaving caller variables unaffected.
Mutating mutable arguments modifies original objects.
Reassigning variable bindings locally does not affect caller bindings.
If you pass a list to a function and call list.append(10), will the list outside the function show the change?
Q12: What is the difference between __new__ and __init__ in Python classes?
__new__(cls, ...): The actual constructor. Allocates and returns a fresh instance of the class in heap memory.__init__(self, ...): The initializer. Takes the instance returned by__new__and configures instance attributes.
class Singleton:
_instance = None
def __new__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instancenew controls instance allocation, making it the hook for implementing singletons.
__new__creates and returns object instances (used in singletons/immutable subclasses).__init__initializes instance attributes.
Which method is executed FIRST when instantiating a Python class instance?
Q13: How does super() work in Python class inheritance?
super() delegates method calls to parent or sibling classes dynamically according to the class's Method Resolution Order (MRO). It ensures cooperative multiple inheritance without hardcoding parent class names.
Delegates execution following Method Resolution Order (MRO).
Essential for cooperative multiple inheritance design.
What method on a class displays its calculated inheritance search order?
Q14: What is C3 Linearization and how does it calculate Method Resolution Order (MRO)?
Python uses the C3 Linearization Algorithm to compute a deterministic MRO for class hierarchies with multiple inheritance. It guarantees:
- Subclasses appear before parents.
- Parent classes maintain list order declared in class headers.
- Preserves local precedence order across complex diamond inheritance graphs.
Algorithm powering Python's Method Resolution Order (MRO).
Prevents diamond inheritance ambiguity errors.
In class D(B, C): pass, which class method is searched first after D?
Q15: What are the differences between @staticmethod and @classmethod?
@classmethod: Receives implicit class binding (cls) as first parameter. Can access/modify class state and acts as alternative constructors.@staticmethod: Isolated utility function bound to class namespace. Receives no implicitselforclsarguments.
class Date:
def __init__(self, day, month, year):
self.day, self.month, self.year = day, month, year
@classmethod
def from_string(cls, date_str):
day, month, year = map(int, date_str.split('-'))
return cls(day, month, year) # Alternative factory constructorclassmethod acts as a factory constructing instances from alternate string formats.
@classmethodreceivesclsbinding; ideal for alternative factory constructors.@staticmethodreceives no implicit binding; ideal for utility functions.
Which decorator receives the class itself (cls) as its first implicit parameter?
Q16: What are Python Descriptors and how do __get__ and __set__ operate?
A Descriptor is an object defining attribute access behavior via __get__(), __set__(), or __delete__() methods. Powers @property, @classmethod, @staticmethod, and ORM field mappings.
class BoundedNumber:
def __init__(self, min_val, max_val):
self.min_val = min_val
self.max_val = max_val
def __set_name__(self, owner, name):
self.name = name
def __set__(self, instance, value):
if not (self.min_val <= value <= self.max_val):
raise ValueError(f"{self.name} out of bounds")
instance.__dict__[self.name] = valueDescriptors intercept attribute writes (set) to validate values systematically.
Enables custom attribute management logic.
Powers properties, methods, and ORM fields under the hood.
Which built-in Python decorator is implemented as a data descriptor?
Q17: How does the @property decorator manage encapsulation?
The @property decorator converts a method into a read-only attribute getter. Paired with @<name>.setter and @<name>.deleter, it enforces encapsulation and input validation without changing public interface attribute access syntax.
Provides getter/setter encapsulation with standard attribute access syntax.
Enables read-only or validated instance attributes.
How do clients access a property method named 'balance' decorated with @property?
Q18: What is __slots__ and how does it reduce instance memory usage?
By default, Python instances store attributes inside a dynamic __dict__ dictionary (causing memory overhead). Declaring __slots__ = ('attr1', 'attr2') replaces __dict__ with a fixed-size compact array layout, reducing instance memory footprint by up to 60-80%.
Eliminates per-instance
__dict__dynamic dictionary allocations.Drastically lowers memory footprint for classes instantiated millions of times.
Can you assign arbitrary new attribute names to an instance of a class that defines slots?
Q19: How do Abstract Base Classes (ABC) enforce interface contracts?
Using abc.ABC and @abstractmethod marks methods that must be implemented by concrete subclasses. Instantiating a subclass that lacks overrides for abstract methods throws a TypeError at runtime instantiation.
Enforces sub-class method implementation contracts.
Prevents direct instantiation of incomplete interface classes.
When is a TypeError raised if a subclass fails to implement an @abstractmethod?
Q20: How does Python manage memory (Reference Counting vs Generational GC)?
Python memory management relies on two layers:
- Reference Counting: Increments/decrements object reference counters. Deallocates objects immediately when references drop to 0.
- Generational Cyclic GC: Detects and breaks cyclic reference graphs across 3 generation tiers (Gen 0, Gen 1, Gen 2) using mark-and-sweep passes.
Reference counting handles immediate deallocation.
Generational GC breaks cyclic references (where objects reference each other).
Which issue CANNOT be resolved by Reference Counting alone, requiring the Generational Garbage Collector?
Q21: What is the Global Interpreter Lock (GIL) and how does it affect multi-threading?
The GIL is a mutual exclusion lock in CPython preventing multiple native threads from executing Python bytecode simultaneously on separate CPU cores. Thus, multi-threading benefits I/O-bound applications, while CPU-bound tasks require multiprocessing to bypass the GIL.
Prevents multi-core execution of CPython bytecode across threads.
Use
threadingfor I/O-bound tasks; usemultiprocessingor C-extensions for CPU-bound tasks.
Which module bypasses the GIL for CPU-heavy mathematical calculations by spawning independent OS processes?
Q22: What is a Python Decorator and how does it transform functions?
A decorator is a callable that accepts a function object as an argument and returns a modified wrapper function object. Syntax @decorator is syntactic sugar for fn = decorator(fn).
from functools import wraps
def repeat(num_times):
def decorator(func):
@wraps(func) # Preserves docstrings and name
def wrapper(*args, **kwargs):
for _ in range(num_times):
result = func(*args, **kwargs)
return result
return wrapper
return decoratorParametrized decorators use three nested function layers to consume arguments.
Syntactic sugar for function wrapping:
fn = decorator(fn).Use
functools.wrapsto preserve wrapped function metadata (__name__,__doc__).
Why should @functools.wraps(func) be applied to wrapper functions inside custom decorators?
Q23: How do Generators and the 'yield' statement operate?
Functions containing yield return a Generator Iterator. When next() is called, execution proceeds until reaching yield, returning the value and suspending execution frame state in memory. Subsequent next() calls resume execution immediately following yield.
Suspends function execution state without destroying frame memory.
Provides lazy evaluation and stream processing with $O(1)$ memory usage.
What exception is raised when a generator exhausts all yielded values during iteration?
Q24: What is 'yield from' and how does generator delegation work?
yield from <iterable> delegates generator yielding directly to a sub-iterable or sub-generator. It establishes a transparent bidirectional channel for passing values and exceptions between outer callers and sub-generators.
Delegates iteration directly to inner generators or iterables.
Establishes bidirectional communication for values and exceptions.
What is the primary code readability benefit of yield from sub_gen over for x in sub_gen: yield x?
Q25: How do Context Managers and the 'with' statement operate under the hood?
The with statement manages resource lifecycles via the Context Manager Protocol:
- Invokes
__enter__()on setup, assigning return value to target variable (as var). - Guarantees invocation of
__exit__(exc_type, exc_val, exc_tb)on block exit, handling exceptions cleanly.
class ManagedFile:
def __init__(self, filename):
self.filename = filename
def __enter__(self):
self.file = open(self.filename, 'w')
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
if self.file:
self.file.close()
return False # Propagate exceptions if any occurredexit guarantees file stream closure even if exceptions are thrown inside the with block.
Executes deterministic cleanup via
__enter__and__exit__.Can also implement using
@contextlib.contextmanagerdecorator.
What does returning True from an exit method accomplish when an exception occurs inside a with block?
Q26: How does asyncio execute concurrent I/O using an Event Loop?
asyncio uses single-threaded cooperative multitasking. An Event Loop manages a queue of pending tasks. Coroutines (async def) yield control explicitly using await, allowing the event loop to execute other ready tasks while waiting for I/O.
Single-threaded cooperative concurrency.
Use
awaiton asynchronous calls to yield loop execution to other tasks.
What happens if you execute a blocking synchronous function (like time.sleep(5)) inside an asyncio coroutine?
Q27: When should you select Threading vs Multiprocessing vs Asyncio?
asyncio: Best for high-concurrency network I/O (WebSockets, microservices) with single-threaded cooperative execution.threading: Best for blocking file/disk I/O or library integrations constrained by GIL.multiprocessing: Best for CPU-bound calculations (data processing, image manipulation), bypassing the GIL via separate OS processes.
Asyncio: Massive network I/O concurrency.
Threading: Blocking I/O tasks.
Multiprocessing: Heavy CPU computation.
Which module provides optimal performance for parallelizing image transformations across a 16-core CPU?
Q28: What is a Metaclass and how does 'type' instantiate classes?
A Metaclass is the 'class of a class'. Just as objects are instances of classes, classes are instances of metaclasses. The default metaclass in Python is type. Metaclasses intercept class construction to inspect, modify, or validate class attributes during import time.
class UpperAttributeMeta(type):
def __new__(cls, name, bases, dct):
# Convert all attribute names to uppercase at class creation time
uppercase_dct = {k.upper(): v for k, v in dct.items() if not k.startswith('__')}
return super().__new__(cls, name, bases, uppercase_dct)
class CustomClass(metaclass=UpperAttributeMeta):
feature = "data"Metaclass intercepts class creation to modify class attribute dictionaries dynamically.
typeis the default metaclass for all Python classes.Metaclasses customize class creation (
__new__/__init__ontype).
What is the return value of type(int) and type(type) in Python?
Q29: How does @functools.lru_cache implement memoization?
@functools.lru_cache(maxsize=128) wraps functions with a Least Recently Used (LRU) Cache hash table. Calls with identical arguments return cached results instantly ($O(1)$), bypassing computation overhead.
Memoizes function call results using an internal dictionary.
Arguments passed to cached functions MUST be hashable.
What happens if you pass a mutable list argument to a function decorated with @functools.lru_cache?
Q30: What are the primary data structures provided by the 'collections' module?
defaultdict: Returns default values for missing keys automatically.Counter: Hash map subclass tracking element frequencies.deque: Doubly linked list/array with fast $O(1)$ appends and pops at both ends.ChainMap: Groups multiple dictionaries into a single updates-searchable view.
defaultdict: Avoids key existence checks.deque: Fast double-ended queue ($O(1)$ operations).Counter: Element frequency counting.
What is the time complexity of popping an element from the LEFT side (popleft()) of a collections.deque?