What does the following code output? from itertools import groupby data = [(‘a’, 1), (‘a’, 2), (‘b’, 3), (‘a’, 4)] for key, group in groupby(data, key=lambda x: x[0]): print(key, list(group))
Python ProfessionalHard
Python Professional — Hard
What does the following code output? from itertools import groupby data = [(‘a’, 1), (‘a’, 2), (‘b’, 3), (‘a’, 4)] for key, group in groupby(data, key=lambda x: x[0]): print(key, list(group))
Explanation
The code uses itertools groupby to group elements in the list 'data' by the first element of each tuple. It outputs the groups with their corresponding keys. In this case, it groups ('a',1) and ('a',2) together, then ('b',3) separately, and finally ('a',4) alone.
Key points
The groupby function groups elements based on a key function