ProgrammingVery hardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
print([y for x in [1, 2, 3] if (y := x + 1) % 2 == 0])
  1. A. [4]
  2. B. [2, 4]
  3. C. [2, 3, 4]
  4. D. [3]

Correct answer: B. [2, 4]

y is x + 1, so the values are 2, 3, 4. Only the even ones, 2 and 4, pass the filter, and the condition is evaluated before y is used.

More Python Programming questions

Exams that ask this topic