PCEP-30-02 · Question #208
``python def func(item): item += [1] data = [1, 2, 3, 4] func(data) print(len(data)) `` What is the expected output of the following code?
The correct answer is A. 5. Option A is correct because += on a Python list performs in-place mutation via __iadd__, which is equivalent to calling item.extend([1]). This modifies the original list object that data points to, appending 1 to it - so data becomes [1, 2, 3, 4, 1] with length 5. B (4) is…
Question
def func(item):
item += [1]
data = [1, 2, 3, 4]
func(data)
print(len(data))
What is the expected output of the following code?Options
- A5
- B4
- C2
- DThe code is erroneous.
How the community answered
(36 responses)- A75% (27)
- B14% (5)
- C8% (3)
- D3% (1)
Explanation
Option A is correct because += on a Python list performs in-place mutation via __iadd__, which is equivalent to calling item.extend([1]). This modifies the original list object that data points to, appending 1 to it - so data becomes [1, 2, 3, 4, 1] with length 5.
B (4) is wrong because it assumes += rebinds the local variable like item = item + [1] would - but for lists, += mutates the existing object rather than creating a new one, so the change is visible outside the function. C (2) has no logical basis in this code. D is wrong because the code is syntactically and semantically valid; it runs cleanly with no exceptions.
Memory tip: Think of list += other as "extend in place" (changes the original) vs. list = list + other as "create a new list" (original unchanged). When in doubt, ask: does += call extend or =? For lists, it always calls extend.
Community Discussion
No community discussion yet for this question.