ProgrammingHardCAT · MBA placement

What is printed?

What is printed?
from itertools import islice, count, takewhile
sq = (i * i for i in count(1))
print(list(islice(sq, 3)), list(takewhile(lambda x: x < 30, (i * i for i in count(1)))), next(sq))
  1. A. [1, 4, 9] [1, 4, 9, 16] 16
  2. B. [1, 4] [1, 4, 9, 16, 25] 9
  3. C. [1, 4, 9] [1, 4, 9, 16, 25] 9
  4. D. [1, 4, 9] [1, 4, 9, 16, 25] 16

Correct answer: D. [1, 4, 9] [1, 4, 9, 16, 25] 16

islice takes three values from the shared generator, so next(sq) continues at 16. takewhile uses a fresh generator and stops at the first square that is not below 30.

More Python Programming questions

Exams that ask this topic