Back to Blog
Blogs 8 min read

Python Programming MCQ with Explanations: Deep Core Mechanics

Test your knowledge of Python’s runtime behavior, memory handling, and scoping rules with this detailed multiple‑choice quiz that includes explanations.

Himanshu Garg
Himanshu Garg November 26, 2026 0 views
python programming mcq with explanations - Python Programming MCQ with Explanations: Deep Core Mechanics

Test your knowledge of Python’s runtime behavior, memory handling, and scoping rules with this detailed multiple‑choice quiz that includes explanations.

Quick answer

This specialized Python programming MCQ with explanations looks at the hardest runtime features of the language. Instead of checking just syntax, the questions deal with mutable default arguments, late‑binding closures, object identity, and decorator metadata. Knowing how these work lets developers avoid hidden logic bugs, use memory more efficiently, and write code that behaves predictably in production distributed systems.

Evaluating Mutable Default Arguments in CPython

To build reliable systems, engineers must understand how the interpreter processes function definitions. A common source of production bugs is the misuse of mutable default arguments. When a function is defined, Python evaluates its default arguments exactly once, at definition time, and stores them in the function object's __defaults__ attribute.
Consider this Python programming MCQ with explanations to test your grasp of this mechanism:

def append_item(val, list_arg=[]):
    list_arg.append(val)
    return list_arg
print(append_item(1))
print(append_item(2, []))
print(append_item(3))

Options:
A) [1], [2], [3]
B) [1], [2], [1, 3]
C) [1], [2], [2, 3]
D) [1], [1, 2], [1, 2, 3]
Correct Answer: B
Explanation:
When append_item is defined, a single list object is instantiated and bound to the default parameter list_arg. The first call, append_item(1), appends 1 to this persistent default list, yielding [1]. The second call explicitly passes a new list, [], which overrides the default parameter; the function appends 2 to this new list and returns [2], leaving the default list untouched. The third call, append_item(3), uses the default argument again, appending 3 to the existing default list, which already contains 1. This results in [1, 3].

For a closely related example, see Raspberry Pi Camera Setup Using Python: Modern Picamera2 Integration.

Comparison of Critical Python Runtime Behaviors

This table summarizes the core mechanics, common failure modes, and engineering mitigations for the key Python runtime concepts covered in the MCQs.

Factor Engineering view Why it matters
Mutable Default Arguments Evaluated once at definition time; shared across all function invocations. Mitigate by using default value None and instantiating the mutable object inside the function body.
Late Binding Closures Variables in closures are resolved at call time, not definition time. Mitigate by binding variables immediately using default arguments in the lambda or inner function signature.
Integer Interning CPython caches integer objects in the range -5 to 256 for memory efficiency. Use equality operator (==) for value comparison instead of identity operator (is) for non-cached ranges.
Decorator Metadata Loss Decorated functions lose their original names, docstrings, and signature metadata. Mitigate by importing and applying the @functools.wraps decorator to the inner wrapper function.

Scope Resolution and Late Binding Closures

Python uses lexical scoping, but closures bind their variables by reference, not by value. This behavior is known as late binding: variables in closures are looked up when the inner function is called, not when it is defined.
Analyze the following code block:

funcs = [lambda: i for i in range(3)]
print([f() for f in funcs])

Options:
A) [0, 1, 2]
B) [2, 2, 2]
C) [0, 0, 0]
D) AttributeError
Correct Answer: B
Explanation:
The list comprehension creates three lambda functions that reference the outer scope variable i. The loop runs, and by the time the comprehension finishes, the variable i in the enclosing scope has reached its final value of 2. When the lambda functions are subsequently executed in the second list comprehension, they all look up the value of i in the enclosing scope and find 2. To avoid this, you must bind the variable at definition time using a default argument, such as lambda x=i: x.

For a closely related example, see The Shaft That Reached 50.9 MPa, Not 25.5.

Memory Management and Object Identity Mechanics

CPython optimizes memory allocation for performance through integer interning. It pre-allocates global integer objects for a specific range of integers, typically from -5 to 256. This optimization affects object identity comparison using the 'is' operator.
Evaluate this behavior:

a = 256
b = 256
c = 257
d = 257
print(a is b, c is d)

Options:
A) True True
B) False False
C) True False
D) False True
Correct Answer: C
Explanation:
The 'is' operator checks for object identity, verifying if both variables point to the exact same memory address. Because 256 falls within CPython's interned integer range (-5 to 256), both a and b point to the same pre-allocated object in memory, making 'a is b' evaluate to True. Conversely, 257 is outside this range. CPython creates two distinct integer objects in memory for c and d, meaning they have different memory addresses, so 'c is d' evaluates to False.

Note that when running this code as a single script file, compile-time optimizations may sometimes merge identical constants, but the standard CPython runtime behavior for interactive environments strictly follows the interning boundary.

For a closely related example, see Effort-Aware Species Distribution Modelling and Connectivity-Graph Optimization of Marine Protected Area Networks in the Mediterranean Sea.

The Mechanism of Mutable Default Argument Accumulation

This flow explains step-by-step how mutable default arguments persist state across separate function calls in CPython.

  1. 1Function Definition
    The interpreter parses the def statement and instantiates the default list object in memory.

    This list is bound to the function's __defaults__ tuple.

  2. 2First Function Call
    The function is called without a second argument. It retrieves the list from __defaults__.

    Modifications are made directly to this shared list object.

  3. 3State Mutation
    The append operation modifies the list in place, updating its state in-memory.

    The function returns a reference to this mutated list.

  4. 4Second Function Call
    The function is called again without a second argument, accessing the exact same __defaults__ list.

    The previous modifications are still present, leading to unexpected data accumulation.

Decorator Execution Order and Metadata Loss

Decorators are syntactic sugar for wrapping functions. However, if not written carefully, decorators can discard critical function metadata, such as the function name (__name__) and docstring (__doc__), which can disrupt logging, monitoring, and debugging tools.
Identify the output of the following implementation:

def my_decorator(f):
    def wrapper(*args, **kwargs):
        return f(*args, **kwargs)
    return wrapper
@my_decorator
def target_func():
    """Target docstring"""
    pass
print(target_func.__name__)

Options:
A) target_func
B) wrapper
C) my_decorator
D) None
Correct Answer: B
Explanation:
Applying the decorator replaces target_func with the inner wrapper function. When you query target_func.__name__, it returns 'wrapper' because the original metadata was not preserved. To maintain the original function's identity and metadata, you must decorate the inner wrapper function with @functools.wraps(f) from the standard library.

Namespace Traversal and the LEGB Lookup Rule

When Python sees a variable name, it looks for it in four places, one after another: the Local (L) namespace, the Enclosing (E) namespace, the Global (G) namespace, and finally the Built-in (B) namespace. Knowing this order helps you avoid accidental name clashes and hidden variables. If you give a variable a value inside a function and you don't use `global` or `nonlocal`, Python treats that variable as local to the function. So, if you try to read a global variable and then assign to the same name inside the function without declaring it, Python will raise an `UnboundLocalError`.

This happens because the compiler has already marked the name as local for the whole function.

Generator State and Exhaustion Dynamics

Generators produce values on demand using the `yield` keyword, maintaining their execution state between calls. Because a generator is an iterator, it can only be traversed once. When it runs out of items, it raises `StopIteration` and becomes exhausted. Any subsequent attempt to retrieve items will raise `StopIteration` immediately. You cannot reset a generator; you must instantiate a new one. This behavior minimizes memory consumption, making generators ideal for processing large data streams. However, you must ensure you do not attempt to reuse an exhausted generator within your data pipelines.

Applying Runtime Gotchas to Production Code

Knowing these subtle execution rules is not just for passing tests; it directly impacts the stability of production applications. When designing microservices, API frameworks, or data-processing pipelines in Python, variable scoping and memory management determine how state is shared. For example, using mutable default values in API route handlers can cause data to leak between requests. Likewise, failing to handle an exhausted generator in an asynchronous stream handler can stall a data-ingestion pipeline. Mastering these concepts allows you to write predictable, high-performance software.

Key takeaways

  • Python evaluates default function arguments exactly once at definition time, meaning mutable defaults persist state across calls.
  • Closures use late binding, resolving variables when the inner function is executed rather than when it is defined.
  • The identity operator (is) checks memory addresses, which can yield surprising results outside CPython's interned integer range (-5 to 256).
  • Unwrapped decorators replace target function metadata, which can be resolved by applying @functools.wraps.
  • The LEGB rule determines namespace search order, and assigning to a variable within a scope marks it as local for the entire block.
  • Generators are single-use iterators that cannot be reset or reused once they raise StopIteration.

Questions engineers often ask

Why does Python evaluate default arguments only once?

Python evaluates default arguments once when the function is defined, not each time it is called. This prevents unnecessary CPU overhead from recalculating defaults on every invocation, especially for complex expressions. While efficient, this behavior means you should use immutable defaults, such as `None`, when dealing with mutable types.

How can I force immediate binding in a Python closure?

You can force immediate binding by using default arguments. If you write `lambda x=i: x` instead of `lambda: i`, the current value of `i` is bound to the parameter `x` at definition time, preventing late-binding lookup issues during execution.

What is the difference between 'is' and '==' in Python?

The `==` operator compares the values of two objects, returning `True` if their data is equal. The `is` operator checks object identity, determining whether both variables point to the exact same memory address. For reliable value comparisons, always use `==`.

Why is UnboundLocalError raised even if the variable is defined globally?

When a variable is assigned a value anywhere inside a function, Python treats that variable as local for the entire function scope. If you attempt to read the variable before the assignment line executes, Python raises an `UnboundLocalError`. In this scenario, Python will not fall back to a global variable of the same name unless you explicitly declare it using the `global` keyword.

Continue learning: python programming mcq with explanations

Explore more deep-dive software architecture and platform engineering resources on the Fried Engineers homepage.

Chat with Fried Engineers