Open In App

Identical Consecutive Grouping in list – Python

Last Updated : 11 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Using itertools.groupby()

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.



Next Article
Article Tags :
Practice Tags :

Similar Reads