Built-ins & Standard Library · Question 16 · Hard

itertools.groupby is applied directly to a string in which one letter appears in two separate runs. What is printed?

from itertools import groupby

print([(k, len(list(g))) for k, g in groupby("aabbba")])
  1. [('a', 3), ('b', 3)]
  2. [('a', 2), ('b', 3), ('a', 1)]
  3. [('a', 2), ('b', 3)]
  4. [('b', 3), ('a', 3)]
Answer and explanation

Answer: B. [('a', 2), ('b', 3), ('a', 1)]

Explanation: groupby only groups items that are next to each other; it does not sort or collect across the whole input. The string has three runs, aa, bbb and a, so a appears as two separate groups.

Previous: sorted is given a key that returns a tuple, to rank students by marks (high to… · Next: Booleans are used in an isinstance check, in addition and inside sum. What…

Practise built-ins & standard library

Try a fresh set of built-ins & standard library questions with an explanation after every answer, free and without signing up: Built-ins & Standard Library practice. Or sit a full placement mock test.

More built-ins & standard library questions

More python practice

Variables, Types & Operators · Python Strings · Lists & Tuples · Dictionaries & Sets · Conditions & Loops · Functions & Scope · Comprehensions & Generators · Classes & Objects

LogicWiz Exams home · All practice topics · Placement mock tests · Daily 10 challenge