Back
+15 XP
Concept

Grouping Data with `itertools.groupby`

`itertools.groupby(data, key)` groups adjacent matching elements into sub-iterators 🗃️. Crucial trap: data MUST be sorted by the grouping key first! 🚨

python
import itertools

words = sorted(["cat", "car", "dog", "duck"], key=lambda w: w[0])
for letter, group in itertools.groupby(words, key=lambda w: w[0]):
    print(letter, list(group))  # c ['cat', 'car'], d ['dog', 'duck'] 🎯

# 25. Grouping Data with `itertools.groupby` `itertools.groupby(data, key)` groups adjacent matching elements into sub-iterators 🗃️. Crucial trap: data MUST be sorted by the grouping key first! 🚨: ```python import itertools words = sorted(["cat", "car", "dog", "duck"], key=lambda w: w[0]) for letter, group in itertools.groupby(words, key=lambda w: w[0]): print(letter, list(group)) # c ['cat', 'car'], d ['dog', 'duck'] 🎯 ``` Unlike SQL `GROUP BY`, Python's `groupby()` only combines consecutive adjacent items. If identical items are separated, it creates brand new duplicate groups unless you sort upfront. 🧠 --- ### Question What catastrophic mistake do beginners make when using `itertools.groupby`? 💀 - [ ] a. Forgetting to sort the data first, resulting in broken, fragmented duplicate groups 🚨 - [ ] b. Passing a list instead of a tuple - [ ] c. Typing groupby in lowercase letters 🔤 - [ ] d. Grouping more than 3 words on a single CPU core 🔥 --- ### Challenge Sort `nums = [1, 2, 1, 2]` with `.sort()`. Group by their value using `itertools.groupby` and print each `(key, len(list(group)))` pair. 🎯 <details> <summary>Solution</summary> ```python import itertools nums = [1, 2, 1, 2] nums.sort() for k, g in itertools.groupby(nums): print(k, len(list(g))) ``` </details>

Checkpoint

What catastrophic mistake do beginners make when using `itertools.groupby`? 💀

Practice

Sort `nums = [1, 2, 1, 2]` with `.sort()`. Group by their value using `itertools.groupby` and print each `(key, len(list(group)))` pair. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks