Wednesday, June 10, 2026
HomeLanguagesitertools.groupby() in Python

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:




# 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))


Output:

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

Example 2 :




# 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)


Output

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

Most Popular

Dominic
32515 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6896 POSTS0 COMMENTS
Nicole Veronica
12012 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12109 POSTS0 COMMENTS
Shaida Kate Naidoo
7019 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6976 POSTS0 COMMENTS
Umr Jansen
6963 POSTS0 COMMENTS