Sometimes, we want to use itertools.groupby() in Python.
In this article, we’ll look at how to use itertools.groupby() in Python.
How to use itertools.groupby() in Python?
To use itertools.groupby() in Python, we can use the groupby
function with a list and a function to return the item to group by.
For instance, we write
from itertools import groupby
things = [('animal', 'bear'), ('animal', 'duck'), ('plant', 'cactus'),
('vehicle', 'speed boat'), ('vehicle', 'school bus')]
for (key, group) in groupby(things, lambda x: x[0]):
for thing in group:
print('A %s is a %s.' % (thing[1], key))
print('')
to call groupby
with the things
list and a function that specifies that we group by the first item in each tuple.
Then a list with the tuples with the group key and the values of the group in a list returned.
Conclusion
To use itertools.groupby() in Python, we can use the groupby
function with a list and a function to return the item to group by.