itertools.groupby() in Python
In this tutorial, we are going to learn about itertools.groupby() function in Python. To use this function firstly, we need to import the itertools module in our code. As the name says that itertools is a module that provides functions that work on iterators(like lists, dictionaries etc.). Moreover, this module makes the programs to run fast and memory-efficient. The output of an itertools function is the iterator object.
groupby() function in Python
Groupby method groups the similar type of object into an iterator object. groupby() function takes two inputs simultaneously they are:-
- iterable(list, dictionary)
If the key isn’t specified then it defaults to the identity function. Meanwhile, the output of the function consists of keys and groups from the iterable.
a = "aaabbbccccd" x = itertools.groupby(a) print(x)
<itertools.groupby object at 0x7f07a5fbd4f8>
In the above example, we have taken the string as iterable(input) and as a result, the output is an iterator object consisting of keys, and groups. Let’s see how to extract the keys and groups from it.
Extracting Keys and Groups in Python
a = "aaabbbccccd" x = itertools.groupby(a) for k,g in x: print(k, g)
a <itertools._grouper object at 0x000001E59C28DBE0> b <itertools._grouper object at 0x000001E59C28D9E8> c <itertools._grouper object at 0x000001E59C28DC18> d <itertools._grouper object at 0x000001E59C28DBE0>
In the above code, we have sent the iterator object into a for loop and printing the keys and groups in it. As a result, we got keys and groups as output but the groups are in the form of itertools.groupby() object. Don’t confuse between itertools object(output of above code containing keys, and groups in iterator object) and itertools.groupby() object(groups datatype of this code output). Let’s also extract the groups.
import itertools a = "aaabbbccccd" x = itertools.groupby(a) for k,g in x: print(k, list(g))
a ['a', 'a', 'a'] b ['b', 'b', 'b'] c ['c', 'c', 'c', 'c'] d ['d']
Lastly, in this example, we are representing the itertools.groupby object in the list format. So the output of the groups is in the list format which consists of similar characters.
In conclusion, groupby function groups the similar type of objects.
Also, read:- Iterators in Python