PCAP 31 03 PCAP Certified Associate Python Programmer · Free Practice Question Easy
Question 3
Q380 - Data Aggregates
What is the expected output of the following code?
- source = [1, 2, 4, 8, 16]
- target = [x // 2 for x in source if x < 10]
- print(target[1])
-
A
- 1
-
B
- 8
-
C
- 2
-
D
- 4
Reveal correct answer
Correct answer: A
Explanation
Topics: list comprehension if expression floor division operator
Try it yourself:
- source = [1, 2, 4, 8, 16]
- target = [x // 2 for x in source if x < 10]
- print(target) # [0, 1, 2, 4]
- print(1 // 2) # 0
- print(target[1]) # 1
Explanation:
The list comprehension will use all the elements that are less than 10
All of the remaining elements will be
divided by 2 with the floor division operator
After that the index 1 will have the value 1
Q380 (Please refer to this number, if you want to write me about this question.)
A. The list comprehension iterates over the elements in the 'source' list and divides each element by 2 if the element is less than 10. In this case, the elements less than 10 are [1, 2, 4, 8]. The 'target' list will contain [0, 1, 2, 4] after the division operation. Therefore, the output of 'print(target[1])' will be 1.
B. The output of the code is not 8. The list comprehension divides each element in the 'source' list by 2 if the element is less than 10. The second element in the 'target' list, which corresponds to 'print(target[1])', is 1, not 8.
C. The output of the code is not 2. The list comprehension divides each element in the 'source' list by 2 if the element is less than 10. The second element in the 'target' list, which corresponds to 'print(target[1])', is 1, not 2.
D. The output of the code is not 4. The list comprehension divides each element in the 'source' list by 2 if the element is less than 10. The second element in the 'target' list, which corresponds to 'print(target[1])', is 1, not 4.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
