QA
Intermediate LevelPython

Why does itertools.groupby() require sorting input data prior to grouping?

❓ Interview Prompt: Explain `itertools.groupby()`, streaming grouping algorithm, consecutive key matching, and sorting input sequences by key.

'itertools.groupby(iterable, key)' groups consecutive elements from an iterable that share matching key values:

CRITICAL REQUIREMENT:

'groupby()' evaluates elements as a single-pass stream! If matching items are not consecutive, it creates duplicate separate groups!

•
Solution: Always sort the input iterable using 'sorted(iterable, key=keyfunc)' BEFORE passing it to 'itertools.groupby()'!

Code Implementation Example

python
from itertools import groupby

data = [{'dept': 'IT', 'name': 'Alice'}, {'dept': 'HR', 'name': 'Bob'}, {'dept': 'IT', 'name': 'Charlie'}]

# MUST sort by group key first!
sorted_data = sorted(data, key=lambda x: x['dept'])

for dept, group in groupby(sorted_data, key=lambda x: x['dept']):
    print(dept, '->', [item['name'] for item in group])
💡Sorting sequences before executing itertools.groupby().
🎯 Interview Key Takeaway

Always sort data by the grouping key before calling itertools.groupby() to ensure complete non-consecutive grouping.

#itertools.groupby#groupby#Sorting#Intermediate
Back to all Python Questions→

More Python Interview Questions

Beginner LevelPython

What is the Python Global Interpreter Lock (GIL) and how does it affect multi-threading?

Beginner LevelPython

What is the difference between a List, Tuple, Set, and Dictionary in Python?

Beginner LevelPython

Why are mutable default arguments (like def func(items=[])) dangerous in Python and how do you fix them?