LearnFrenzy
Sign in Take a free test

Iterators and Generators · Predict the Output · Question 15

takewhile() and groupby() Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 15 Back to Exercise

What is the output of the following Python program?

main.py
from itertools import takewhile, groupby

print(list(takewhile(lambda n: n < 5, [1, 3, 6, 2, 4])))
print([(k, len(list(g))) for k, g in groupby("aaabccaa")])
  • A [1, 3, 2, 4] [('a', 5), ('b', 1), ('c', 2)]
  • B [1, 3] [('a', 5), ('b', 1), ('c', 2)]
  • C [1, 3, 2, 4] [('a', 3), ('b', 1), ('c', 2), ('a', 2)]
  • D [1, 3] [('a', 3), ('b', 1), ('c', 2), ('a', 2)] Correct
Correct Answer: Option D

takewhile stops at the first failing item (6) and never looks further. groupby groups only neighbouring equal items, so the two runs of "a" are separate groups.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links