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
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)- A3% (1)
- B6% (2)
- D11% (4)
- E80% (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
xchanged - 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 as1- it was mutated to42through 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.