ProgrammingVery hardGATE CS · Product-company placement

What is printed? (Output lines are shown separated by " / ".)

What is printed? (Output lines are shown separated by " / ".)
from itertools import groupby
data = [1, 1, 2, 1, 3, 3]
print([(k, len(list(g))) for k, g in groupby(data)])
groups = groupby(data)
saved = [g for k, g in groups]
print(len(saved), [list(g) for g in saved][0])
  1. A. [(1, 3), (2, 1), (3, 2)] / 3 [1, 1, 1]
  2. B. [(1, 2), (2, 1), (1, 1), (3, 2)] / 4 []
  3. C. [(1, 2), (2, 1), (1, 1), (3, 2)] / 4 [1, 1]
  4. D. [(1, 3), (2, 1), (3, 2)] / 3 []

Correct answer: B. [(1, 2), (2, 1), (1, 1), (3, 2)] / 4 []

groupby groups only consecutive equal items, so 1 appears as two separate groups. All groups share one underlying iterator: advancing groupby to the next key exhausts the previous group, so groups saved for later come out empty.

More Python Programming questions

Exams that ask this topic