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
Python | os.getgroups() 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
Combinatoric Iterators in Python An iterator is an object that can be traversed through all its values. Simply put, iterators are data type that can be looped upon. Generators are iterators but as they cannot return values instead they yield results when they are executed, using the 'yield' function. Generators can be recursive jus
4 min read
Itertools Combinations() function - Python The combinations() function in Python, part of the itertools module, is used to generate all possible combinations of a specified length from a given iterable (like a list, string, or tuple). Unlike permutations, where the order does matter, combinations focus only on the selection of elements, mean
2 min read
Python - Itertools.tee() In Python, Itertools is the inbuilt module that allows us to handle the iterators in an efficient way. They make iterating through the iterables like lists and strings very easily. One such itertools function is tee().Note: For more information, refer to Python Itertoolstee() function This iterator
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
Iterate over a list in Python Python provides several ways to iterate over list. The simplest and the most common way to iterate over a list is to use a for loop. This method allows us to access each element in the list directly.Example: Print all elements in the list one by one using for loop.Pythona = [1, 3, 5, 7, 9] # On each
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