What is the output of `print([x**2 for x in range(5) if x % 2 == 0])`?

Answer and explanation

Correct answer: B. `[0, 4, 16]`

  1. Step 1: `range(5)` gives 0 to 4; the condition keeps multiples of 2.
  2. Step 2: Squaring them gives [0, 4, 16].
Answer
`[0, 4, 16]`.
Why not the others: `[1, 9]`, `[0, 2, 4]` and `[4, 16]` do not fit.

Practise more Python programming and algorithms.

Free questions with an explanation for every one, and full timed Saudi Secondary School Certificate mock tests.