ProgrammingHardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
from itertools import takewhile, dropwhile
a = [1, 3, 4, 6, 7, 9]
print(list(takewhile(lambda x: x % 2, a)), list(dropwhile(lambda x: x % 2, a)))
  1. A. [1, 3] [6, 7, 9]
  2. B. [1, 3, 5] [6, 7, 9]
  3. C. [1, 3] [4, 6, 7, 9]
  4. D. [1, 3, 7, 9] [4, 6]

Correct answer: C. [1, 3] [4, 6, 7, 9]

takewhile yields items while the predicate holds and stops at the first failure, which is 4. dropwhile skips the same odd prefix and then yields everything from 4 on, without rechecking later odd items.

More Python Programming questions

Exams that ask this topic