ProgrammingHardTCS NQT · Accenture

What is printed?

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

Correct answer: D. [0, 4, 16]

The walrus assigns y before the test, and the test keeps the even squares 0, 4 and 16 from x = 0, 2 and 4.

More Python Programming questions

Exams that ask this topic