75 Topics
Chapter•390 Minutes

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.

Inspecting Python Bytecode
import dis

def add(a, b):
    return a + b

dis.dis(add) # Disassembles bytecode instructions

The dis module exposes the raw PVM bytecode instructions produced for Python functions.

Key Takeaways
  • Compilation to Bytecode (.pyc) occurs automatically prior to PVM interpretation.

  • Dynamic typing resolves variable types at runtime rather than compile time.

Knowledge Check

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.

Key Takeaways
  • Lists = Mutable, higher memory overhead.

  • Tuples = Immutable, lower memory, hashable (can be dict keys).

Knowledge Check

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.

Key Takeaways
  • Uses hash tables for $O(1)$ average lookups.

  • Python 3.6+ dicts preserve insertion order while reducing memory by ~20-25%.

Knowledge Check

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.

Safe Default Argument Pattern
# ❌ 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 target

Re-assigning target = [] inside function scope creates fresh list allocations per call.

Key Takeaways
  • Default parameter objects bind at function definition time.

  • Use None as default placeholder and assign new mutables inside the body.

Knowledge Check

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__()).
  • is Operator: Checks object identity (verifies if two variables reference the exact same memory address using id(a) == id(b)).
Key Takeaways
  • == tests equivalence of values.

  • is tests memory address identity.

Knowledge Check

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.
Key Takeaways
  • Shallow copy duplicates top-level container only.

  • Deep copy duplicates container and all nested child object references recursively.

Knowledge Check

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.
Forwarding Arguments via Wrapper
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.

Key Takeaways
  • *args collects positional arguments into a tuple.

  • **kwargs collects keyword arguments into a dictionary.

Knowledge Check

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.
Key Takeaways
  • List Comprehension = Eager evaluation ($O(N)$ memory). Generator Expression = Lazy iteration ($O(1)$ memory).

Knowledge Check

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).

Key Takeaways
  • Single-expression inline functions.

  • Useful for short callbacks in map(), filter(), or sorted(key=...).

Knowledge Check

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:

  1. L (Local): Inside active function/lambda body.
  2. E (Enclosing / Nonlocal): In enclosing nested function scopes.
  3. G (Global): At module top-level.
  4. B (Built-in): Preloaded Python built-in names (len, range).
Key Takeaways
  • Scope resolution order: Local -> Enclosing -> Global -> Built-in.

  • Use global or nonlocal keywords to rebind variables in outer scopes.

Knowledge Check

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.
Key Takeaways
  • Mutating mutable arguments modifies original objects.

  • Reassigning variable bindings locally does not affect caller bindings.

Knowledge Check

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.
Overriding __new__ for Singleton Pattern
class Singleton:
    _instance = None
    
    def __new__(cls, *args, **kwargs):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

new controls instance allocation, making it the hook for implementing singletons.

Key Takeaways
  • __new__ creates and returns object instances (used in singletons/immutable subclasses).

  • __init__ initializes instance attributes.

Knowledge Check

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.

Key Takeaways
  • Delegates execution following Method Resolution Order (MRO).

  • Essential for cooperative multiple inheritance design.

Knowledge Check

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:

  1. Subclasses appear before parents.
  2. Parent classes maintain list order declared in class headers.
  3. Preserves local precedence order across complex diamond inheritance graphs.
Key Takeaways
  • Algorithm powering Python's Method Resolution Order (MRO).

  • Prevents diamond inheritance ambiguity errors.

Knowledge Check

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 implicit self or cls arguments.
Classmethod Factory Pattern
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 constructor

classmethod acts as a factory constructing instances from alternate string formats.

Key Takeaways
  • @classmethod receives cls binding; ideal for alternative factory constructors.

  • @staticmethod receives no implicit binding; ideal for utility functions.

Knowledge Check

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.

Custom Validation Descriptor
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] = value

Descriptors intercept attribute writes (set) to validate values systematically.

Key Takeaways
  • Enables custom attribute management logic.

  • Powers properties, methods, and ORM fields under the hood.

Knowledge Check

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.

Key Takeaways
  • Provides getter/setter encapsulation with standard attribute access syntax.

  • Enables read-only or validated instance attributes.

Knowledge Check

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%.

Key Takeaways
  • Eliminates per-instance __dict__ dynamic dictionary allocations.

  • Drastically lowers memory footprint for classes instantiated millions of times.

Knowledge Check

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.

Key Takeaways
  • Enforces sub-class method implementation contracts.

  • Prevents direct instantiation of incomplete interface classes.

Knowledge Check

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:

  1. Reference Counting: Increments/decrements object reference counters. Deallocates objects immediately when references drop to 0.
  2. 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 & Generational Garbage Collector
Key Takeaways
  • Reference counting handles immediate deallocation.

  • Generational GC breaks cyclic references (where objects reference each other).

Knowledge Check

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.

Key Takeaways
  • Prevents multi-core execution of CPython bytecode across threads.

  • Use threading for I/O-bound tasks; use multiprocessing or C-extensions for CPU-bound tasks.

Knowledge Check

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).

Writing a Parametrized Decorator
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 decorator

Parametrized decorators use three nested function layers to consume arguments.

Key Takeaways
  • Syntactic sugar for function wrapping: fn = decorator(fn).

  • Use functools.wraps to preserve wrapped function metadata (__name__, __doc__).

Knowledge Check

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.

Key Takeaways
  • Suspends function execution state without destroying frame memory.

  • Provides lazy evaluation and stream processing with $O(1)$ memory usage.

Knowledge Check

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.

Key Takeaways
  • Delegates iteration directly to inner generators or iterables.

  • Establishes bidirectional communication for values and exceptions.

Knowledge Check

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:

  1. Invokes __enter__() on setup, assigning return value to target variable (as var).
  2. Guarantees invocation of __exit__(exc_type, exc_val, exc_tb) on block exit, handling exceptions cleanly.
Custom Context Manager Class
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 occurred

exit guarantees file stream closure even if exceptions are thrown inside the with block.

Key Takeaways
  • Executes deterministic cleanup via __enter__ and __exit__.

  • Can also implement using @contextlib.contextmanager decorator.

Knowledge Check

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.

Key Takeaways
  • Single-threaded cooperative concurrency.

  • Use await on asynchronous calls to yield loop execution to other tasks.

Knowledge Check

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.
Key Takeaways
  • Asyncio: Massive network I/O concurrency.

  • Threading: Blocking I/O tasks.

  • Multiprocessing: Heavy CPU computation.

Knowledge Check

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.

Creating Custom Metaclass
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.

Key Takeaways
  • type is the default metaclass for all Python classes.

  • Metaclasses customize class creation (__new__ / __init__ on type).

Knowledge Check

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.

Key Takeaways
  • Memoizes function call results using an internal dictionary.

  • Arguments passed to cached functions MUST be hashable.

Knowledge Check

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.
Key Takeaways
  • defaultdict: Avoids key existence checks. deque: Fast double-ended queue ($O(1)$ operations). Counter: Element frequency counting.

Knowledge Check

What is the time complexity of popping an element from the LEFT side (popleft()) of a collections.deque?