nerdexam
Python_Institute

PCEP-30-02 · Question #171

What is the expected output of the following code? ``python def func(p1, p2): p1 = 1 p2[0] = 42 x = 3 y = [1, 2, 3] func(x, y) print(x, y[0]) ``

The correct answer is E. 342. Option E (3 42) is correct because Python passes arguments by object reference: x is an integer (immutable), so reassigning p1 = 1 inside the function only rebinds the local variable - x remains 3. However, y is a list (mutable), and p2[0] = 42 mutates the original list object…

Question

What is the expected output of the following code?
def func(p1, p2):
 p1 = 1
 p2[0] = 42

x = 3
y = [1, 2, 3]

func(x, y)
print(x, y[0])

Options

  • A142
  • BThe code is erroneous.
  • C11
  • D31
  • E342

How the community answered

(35 responses)
  • A
    3% (1)
  • B
    6% (2)
  • D
    11% (4)
  • E
    80% (28)

Explanation

Option E (3 42) is correct because Python passes arguments by object reference: x is an integer (immutable), so reassigning p1 = 1 inside the function only rebinds the local variable - x remains 3. However, y is a list (mutable), and p2[0] = 42 mutates the original list object in place, so y[0] becomes 42.

  • A (142) and C (11) are wrong because they imply x changed - it didn't; integers are immutable and reassigning a local parameter never affects the caller's variable.
  • D (31) is wrong because it implies y[0] stayed as 1 - it was mutated to 42 through the list reference.
  • B is wrong because the code is perfectly valid Python and runs without errors.

Memory tip: Think "rebind vs. mutate" - if a function reassigns a parameter (p1 = 1), the original is untouched; if it mutates the object (p2[0] = 42), the original changes. Immutables (int, str, tuple) can only be rebound; mutables (list, dict) can be changed in place.

Community Discussion

No community discussion yet for this question.

Full PCEP-30-02 Practice