itertools.groupby() in Python

Prerequisites: Python Itertools

Python’s Itertool is a module that provides various functions that work on iterators to produce complex iterators. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra.

Itertools.groupby()

This method calculates the keys for each element present in iterable. It returns key and iterable of grouped items.

Syntax: itertools.groupby(iterable, key_func)

Parameters:
iterable: Iterable can be of any kind (list, tuple, dictionary).
key: A function that calculates keys for each element present in iterable.



Return type: It returns consecutive keys and groups from the iterable. If the key function is not specified or is None, key defaults to an identity function and returns the element unchanged.

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to demonstrate 
# itertools.groupby() method 
  
  
import itertools
  
  
L = [("a", 1), ("a", 2), ("b", 3), ("b", 4)]
  
# Key function
key_func = lambda x: x[0]
  
for key, group in itertools.groupby(L, key_func):
    print(key + " :", list(group))

chevron_right


Output:

a : [('a', 1), ('a', 2)]
b : [('b', 3), ('b', 4)]

Example 2 :

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to demonstrate 
# itertools.groupby() method 
  
  
import itertools
  
  
a_list = [("Animal", "cat"), 
          ("Animal", "dog"), 
          ("Bird", "peacock"), 
          ("Bird", "pigeon")]
  
  
an_iterator = itertools.groupby(a_list, lambda x : x[0])
  
for key, group in an_iterator:
    key_and_group = {key : list(group)}
    print(key_and_group)

chevron_right


Output

{'Animal': [('Animal', 'cat'), ('Animal', 'dog')]}
{'Bird': [('Bird', 'peacock'), ('Bird', 'pigeon')]}



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.