PCAP 31 03 PCAP Certified Associate Python Programmer · Free Practice Question Easy
Question 59
Q255 - Data Aggregates
What is the expected output of the following code?
- data = [[0, 1, 2, 3] for i in range(2)]
- print(data[2][0])
-
A
2 -
B
1 -
C
The code is erroneous.
-
D
0
Reveal correct answer
Correct answer: C
Explanation
Topics: list comprehension list indexing IndexError
Try it yourself:
- data = [[0, 1, 2, 3] for i in range(2)]
- print(data[2][0]) # IndexError: list index out of range
- print(data) # [[0, 1, 2, 3], [0, 1, 2, 3]]
- print(data[0]) # [0, 1, 2, 3]
- print(data[1]) # [0, 1, 2, 3]
Explanation:
range(2) has two elements: 0 and 1
Therefore the outer list will have two elements.
And data[2] does not exist.
Q255 (Please refer to this number, if you want to write me about this question.)
A. The code will not output 2 because it is trying to access the element at index 0 of the third element in the data list, which does not exist. This will result in an IndexError rather than printing the value 2.
B. The code will not output 1 because it is trying to access the element at index 0 of the third element in the data list, which does not exist. This will result in an IndexError rather than printing the value 1.
C. The code is erroneous because it tries to access an index that is out of bounds in the data list. The data list has only two elements, indexed at 0 and 1, so trying to access data[2] will result in an IndexError.
D. The code will not output 0 because it is trying to access the element at index 0 of the third element in the data list, which does not exist. This will result in an IndexError rather than printing the value 0.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
