Certified Associate in Python Programming (PCAP-31-03) — Question 87
What is the expected behavior of the following code?
my_list = [i for i in range(5)]
m = [my_list[i] for i in range(5) if my_list[i] % 2 != 0]
print(m)
Answer options
- A. the code is erroneus and it will not execute
- B. it outputs [0, 2, 4]
- C. it outputs [0, 1, 2, 3, 4]
- D. it outputs [1, 3]
Correct answer: D
Explanation
The correct answer is D because the code filters the list to include only odd numbers. The list comprehension evaluates each item in 'my_list', and since only 1 and 3 are odd, they are included in the output, while the other options do not match the expected result.