What is the output of the following Python expression: `[x**2 for x in range(5) if x % 2 == 1]`?

Answer and explanation

Correct answer: B. `[1, 9]`

  1. Step 1: The `range(5)` function generates integers .
  2. Step 2: The condition `if x % 2 == 1` filters for odd numbers: and . Squaring them yields and , producing `[1, 9]`.
Answer
`[1, 9]`.
Why not the others: '`[0, 4, 16]`' filters for even numbers; '`[1, 4, 9]`' includes even number 2; '`[0, 1, 4, 9, 16]`' squares all numbers without filtering.

Practise more Python Programming, Data Structures, Algorithms, Networks and Cybersecurity.

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

What is the output of… | Saudi Secondary School Certificate