Identical Consecutive Grouping in list – Python
Last Updated :
11 Feb, 2025
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 result would be [[4, 4], [5, 5, 5], [7, 7], [8, 8, 8]], as identical elements are grouped based on their occurrence sequence.
groupby() from the itertools module to efficiently group consecutive identical elements. It automatically detects adjacent duplicates and groups them together, making it the most optimized and widely used approach.
Python
from itertools import groupby
a = [4, 4, 5, 5, 5, 7, 7, 8, 8, 8]
res = [list(y) for x, y in groupby(a)]
print(str(res))
Output[[4, 4], [5, 5, 5], [7, 7], [8, 8, 8]]
Explanation:[list(y) for x, y in groupby(a)] extracts these groups and converts them into sublists.
Using loop
A straightforward approach where we iterate through the list while keeping track of consecutive identical elements. When a different element appears, we start a new group. This method is easy to implement and does not require external libraries.
Python
a = [4, 4, 5, 5, 5, 7, 7, 8, 8, 8]
res = [] # initialize empty list
temp = [a[0]] # initialize `temp` with the first element
for i in range(1, len(a)):
if a[i] == a[i - 1]:
temp.append(a[i])
else:
res.append(temp)
temp = [a[i]]
res.append(temp) # Append the last group
print(res)
Output[[4, 4], [5, 5, 5], [7, 7], [8, 8, 8]]
Explanation: for loop iterates through a, adding elements to temp if they match the previous one. When a different element appears, temp is added to res and a new group starts. Finally, the last group is appended to res .
Using reduce()
This method applies functional programming by using reduce() from functools to accumulate elements into grouped sublists . It eliminates explicit loops but can be harder to read and slightly less intuitive compared to other methods.
Python
from functools import reduce
a = [4, 4, 5, 5, 5, 7, 7, 8, 8, 8]
res = reduce(lambda acc, x: acc[:-1] + [acc[-1] + [x]] if acc and acc[-1][0] == x else acc + [[x]], a, [])
print(res)
Output[[4, 4], [5, 5, 5], [7, 7], [8, 8, 8]]
Explanation: It iterates through a, checking if the current element x matches the last group’s first element. If it does, x is appended to that group, otherwise a new group is started.
Using recursion
A recursive approach that processes the list element by element, grouping identical consecutive elements. While effective, this method is less optimal for large lists due to Python’s recursion depth limits. It is useful for understanding recursion concepts.
Python
# function defination
def fun(lst, index=0, res=None):
if res is None: # Initialize result list on first call
res = []
if index >= len(lst): # Base case
return res
# If result list is empty or current element is different from the last group
if not res or lst[index] != res[-1][0]:
res.append([lst[index]])
else:
res[-1].append(lst[index])
return fun(lst, index + 1, res) # Recursive call
a = [4, 4, 5, 5, 5, 7, 7, 8, 8, 8]
print(fun(a))
Output[[4, 4], [5, 5, 5], [7, 7], [8, 8, 8]]
Explanation: This function initializes res and iterates recursively. The base case returns res when index reaches the end. If res is empty or the current element differs from the last group, a new group is created, otherwise the element is appended. The recursion continues until all elements are grouped.
Similar Reads
Python | Consecutive elements grouping in list
Sometimes, while working with Python lists, we can have a problem in which we might need to group the list elements on basis of their respective consecutiveness. This kind of problem can occur while data handling. Let's discuss certain way in which this task can be performed. Method 1: Using enumera
5 min read
Python | Consecutive duplicates all elements deletion in list
Sometimes, while working with Python list, a problem can occur to filter list to remove duplicates. The solution to this has been discussed before. But sometimes, we may have a problem in which we need to delete the duplicate and element itself if it occurs more than 1 in consecution. This type of p
4 min read
Python | Consecutive remaining elements in list
Sometimes, while working with Python list, we can have a problem in which we need to get the consecutive elements count remaining( including current ), to make certain decisions beforehand. This can be a potential subproblem of many competitive programming competitions. Let's discuss a shorthand whi
2 min read
Python | Remove consecutive duplicates from list
Removing consecutive duplicates from a list means eliminating repeated elements that appear next to each other in the list. If an element repeats consecutively, only the first occurrence should remain and the duplicates should be removed. Example:Input: ['a', 'a', 'b', 'b', 'c', 'a', 'a', 'a'] Outpu
3 min read
Python | Check if two lists are identical
In this article we will explore various methods to check if two lists are identical or not. By "identical", we mean that the lists contain the same elements in the same order. The simplest way to check if two lists are identical using the equality operator (==). Using Equality Operator (==)The easie
2 min read
Python - Find all elements count in list
In Python, counting the occurrences of all elements in a list is to determine how many times each unique element appears in the list. In this article, we will explore different methods to achieve this. The collections.Counter class is specifically designed for counting hashable objects. It provides
3 min read
Python | Count of common elements in the lists
Sometimes, while working with Python list we can have a problem in which we have to compare two lists for index similarity and hence can have a task of counting equal index pairs. Let's discuss certain ways in which this task can be performed. Method #1: Using sum() + zip() This task can be performe
5 min read
itertools.groupby() in Python
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: [GFGTABS]
3 min read
How to Compare List of Dictionaries in Python
Comparing a list of dictionaries in Python involves checking if the dictionaries in the list are equal, either entirely or based on specific key-value pairs. This process helps to identify if two lists of dictionaries are identical or have any differences. The simplest approach to compare two lists
3 min read
What is the fastest way to drop consecutive duplicates a List[int] column?
Dropping consecutive duplicates involves removing repeated elements that appear next to each other in a list, keeping only the first occurrence of each sequence. For example, given the list [1, 2, 2, 3, 3, 3, 4], the result should be [1, 2, 3, 4] because the duplicates immediately following the same
3 min read