ProgrammingVery hardTCS NQT · Infosys HackWithInfy · Product Company SDE

What does the following Python 3 code print? import itertools print(list(itertools.takewhile(lambda x: x < 3, [1, 2, 3, 4, 1, 2])))

  1. A. [1, 2]
  2. B. [1, 2, 1, 2]
  3. C. [3, 4]
  4. D. [1, 2, 3]

Correct answer: A. [1, 2]

takewhile stops at the first element that fails the predicate (3) and never looks past it, even though later elements (1,2) would also pass.

More Python Programming questions

Exams that ask this topic