PCEP-30-02 · Question #44
What is the expected output of the following code? data = [[0, 1, 2, 3] for i in range(2)] print(data[2][0])
The correct answer is A. The code is erroneous. range(2) yields only 0 and 1, so the list comprehension produces exactly two inner lists - valid indices are 0 and 1 only. Accessing data[2] raises an IndexError at runtime, making the code erroneous (A correct). Why the distractors fail: D (0) - A plausible trap: data[0][0]…
Question
Options
- AThe code is erroneous.
- B2
- C1
- D0
How the community answered
(31 responses)- A77% (24)
- B6% (2)
- C3% (1)
- D13% (4)
Explanation
range(2) yields only 0 and 1, so the list comprehension produces exactly two inner lists - valid indices are 0 and 1 only. Accessing data[2] raises an IndexError at runtime, making the code erroneous (A correct).
Why the distractors fail:
- D (0) - A plausible trap:
data[0][0]would be0, but the outer index here is2, not0. - B (2) - Another index confusion:
data[0][2]would be2, but again, the outer index2is out of range before the inner index is ever reached. - C (1) - No valid index combination in this structure produces
1fromdata[x][0]; the first element of every inner list is0.
Memory tip: When you see range(n) in a list comprehension, the resulting list has exactly n elements (indices 0 through n-1). Here, range(2) → 2 elements → max index is 1, so any access at index 2 or higher will always crash.
Community Discussion
No community discussion yet for this question.