itertools.groupby() in Python
Last Updated :
21 Mar, 2025
The itertools.groupby() function in Python is part of the itertools module and is used for grouping consecutive elements of an iterable that have the same value. It generates a group of consecutive elements from an iterable and returns them as tuples containing a key and a group.
Example:
Python
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))
Outputa : [('a', 1), ('a', 2)]
b : [('b', 3), ('b', 4)]
Explanation: In this code, itertools.groupby() groups the list of tuples based on the first element of each tuple. The key function (key_func) extracts the first element of each tuple (x[0]). The groupby() function then categorizes the tuples into groups with the same first element, and each group is displayed in the output.
Syntax
itertools.groupby(iterable, key=None)
Parameters
- iterable: This is the iterable (like a list, tuple, string, etc.) whose elements are to be grouped.
- key (optional): A function to compute a key value for each element. This is used for grouping, and by default, it is None. When None, the elements are grouped based on their actual value.
Return Value
The groupby() method returns an iterator of consecutive (key, group) pairs. Each group is itself an iterator, containing consecutive elements from the iterable that share the same key.
Examples of itertools.groupby()
1. Grouping Consecutive Even and Odd Numbers
This example demonstrates how to use itertools.groupby() to group consecutive numbers into even and odd categories.
Python
import itertools
# List of numbers
a = [2, 4, 6, 7, 8, 10, 11, 12, 13]
# Grouping consecutive even and odd numbers
g_data = itertools.groupby(a, key=lambda x: 'Even' if x % 2 == 0 else 'Odd')
# Display grouped elements
for key, group in g_data:
print(f"Group: {key} -> {list(group)}")
OutputGroup: Even -> [2, 4, 6]
Group: Odd -> [7]
Group: Even -> [8, 10]
Group: Odd -> [11]
Group: Even -> [12]
Group: Odd -> [13]
Explanation: This example groups numbers into consecutive even and odd numbers. The groupby() function checks the parity of each number and forms groups accordingly. The output shows the even and odd groups.
2. Grouping Strings Based on Length
In this example, itertools.groupby() is used to group strings based on their length, categorizing words into groups of equal length.
Python
import itertools
# List of strings
l = ['apple', 'banana', 'cherry', 'date', 'fig', 'grape']
# Grouping strings by their length
g_data = itertools.groupby(l, key=lambda x: len(x))
# Display grouped elements
for key, group in g_data:
print(f"Length: {key} -> {list(group)}")
OutputLength: 5 -> ['apple']
Length: 6 -> ['banana', 'cherry']
Length: 4 -> ['date']
Length: 3 -> ['fig']
Length: 5 -> ['grape']
Explanation: Here, words are grouped by their length using the groupby() function. It categorizes the words into groups of the same length, and the output displays these groups.
Similar Reads
Itertools in Python3 Itertools is a module in Python, it is used to iterate over data structures that can be stepped over using a for-loop. Such data structures are also known as iterables. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra. Wh
3 min read
Python | os.getgrouplist() method OS module in Python provides functions for interacting with the operating system. OS comes under Pythonâs standard utility modules. This module provides a portable way of using operating system dependent functionality. All functions in os module raise OSError in the case of invalid or inaccessible f
2 min read
Itertools.accumulate()-Python itertools.accumulate() is an iterator that takes two arguments, an iterable (target) and an optional function. The function is applied at each iteration to accumulate the result. By default, if no function is provided, it performs addition. If the input iterable is empty, the output will also be emp
3 min read
Python List count() method The count() method is used to find the number of times a specific element occurs in a list. It is very useful in scenarios where we need to perform frequency analysis on the data.Let's look at a basic example of the count() method.Pythona = [1, 2, 3, 1, 2, 1, 4] c = a.count(1) print(c)Output3 Explan
2 min read
Print lists in Python Printing a list in Python is a common task when we need to visualize the items in the list. There are several methods to achieve this and each is suitable for different situations. In this article we explore these methods.The simplest way of printing a list is directly with the print() function:Pyth
3 min read
How to Iterate over Dataframe Groups in Python-Pandas? In this article, we'll see how we can iterate over the groups in which a data frame is divided. So, let's see different ways to do this task. First, Let's create a data frame: Python3 # import pandas library import pandas as pd # dictionary dict = {'X': ['A', 'B', 'A', 'B'], 'Y': [1, 4, 3, 2]} # cre
2 min read
Identical Consecutive Grouping in list - Python The task of Identical Consecutive Grouping in a list involves grouping consecutive identical elements together while preserving their order. Given a list, the goal is to create sublists where each contains only identical consecutive elements. For example, with a = [4, 4, 5, 5, 5, 7, 7, 8, 8, 8], the
3 min read
Python | Group elements on break positions in list Many times we have problems involving and revolving around Python grouping. Sometimes, we might have a specific problem in which we require to split and group N element list on missing elements. Let's discuss a way in which this task can be performed. Method : Using itemgetter() + map() + lambda() +
2 min read
Python | Group strings at particular element in list Sometimes, while working with Python list, we can have a problem in which we have to group strings in a way that at occurrence of particular element, the string list is grouped. This can be a potential problem of day-day programming. Let's discuss certain way in which this problem can be performed.
7 min read
Python Counter.update() Method Python's Counter is a subclass of the dict class and provides a convenient way to keep track of the frequency of elements in an iterable. The Counter.update() method is particularly useful for updating the counts of elements in a Counter object based on another iterable or another Counter object. In
2 min read