Open In App
Related Articles

itertools.groupby() in Python

Improve Article
Improve
Save Article
Save
Like Article
Like

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')]}

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 30 Jan, 2020
Like Article
Save Article
Similar Reads
Related Tutorials