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")])
- [('a', 3), ('b', 3)]
- [('a', 2), ('b', 3), ('a', 1)]
- [('a', 2), ('b', 3)]
- [('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
- A file tools.py ends with a block under if __name__ == "__main__":. When does…
- itertools is used to count the 2-item combinations and the 2-item permutations…
- sorted is given a key that returns a tuple, to rank students by marks (high to…
- Booleans are used in an isinstance check, in addition and inside sum. What…
- A program imports the same module helper from two different files. How many…
- A defaultdict(int) is updated for one key, read for a second key and tested…
- all, any and max are each given an empty list, with a default supplied to max…
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