ProgrammingHardTCS NQT · Accenture
What is printed?
What is printed?
vals = [y for x in range(5) if (y := x * x) % 2 == 0] print(vals)
- A. [0, 1, 4, 9, 16]
- B. [4, 16]
- C. [0, 4, 9, 16]
- 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
- What is printed? python from functools import partial f = partial(int, base=2) print(f('101'), f('11', base=10))
- What is printed? python print(list(zip([(1, 'a'), (2, 'b')])))
- What is printed? python print(1 if 0 else 2 if 1 else 3, (lambda: 1 if False else 'x')())
- What is printed? python print(type(1/1).name, type(1//1).name, type(2-1).name, type(21).name)
- What is printed? python print(sorted({x % 4 for x in range(10)}))
- What is printed? python print('xxhixx'.strip('x') + '|' + 'abc'.strip('ac'))