Open In App

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 enumerate() + groupby() + generator function + lambda This task can be performed using the combination of above functions. In this, we create a generator function, in which we pass the list whose index-element are accessed using enumerate() and grouped by consecutive elements using groupby() and lambda. Works with Python2 only 






# Python code to demonstrate working of
# Consecutive elements grouping list
# using enumerate() + groupby() + generator function + lambda
import itertools
 
# Utility Generator Function
def groupc(test_list):
    for x, y in itertools.groupby(enumerate(test_list), lambda (a, b): b - a):
        y = list(y)
        yield y[0][1], y[-1][1]
 
# initialize list
test_list = [1, 2, 3, 6, 7, 8, 11, 12, 13]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Consecutive elements grouping list
# using enumerate() + groupby() + generator function + lambda
res = list(groupc(test_list))
 
# printing result
print("Grouped list is : " + str(res))

Output : 
The original list is : [1, 2, 3, 6, 7, 8, 11, 12, 13]
Grouped list is : [(1, 3), (6, 8), (11, 13)]

Time complexity: O(n), where n is the length of the input list. 
Auxiliary space: O(1)



Method 2: Using a while loop:

Use two nested while loops to find consecutive elements in the list. The outer loop iterates over the elements in the list, and the inner loop finds the end of the consecutive sequence. The result is stored in a list of tuples, with each tuple containing the first and last elements of a consecutive sequence.




def group_consecutive(test_list):
    result = []
    i = 0
    while i < len(test_list):
        j = i
        while j < len(test_list) - 1 and test_list[j+1] == test_list[j]+1:
            j += 1
        result.append((test_list[i], test_list[j]))
        i = j + 1
    return result
 
# initialize list
test_list = [1, 2, 3, 6, 7, 8, 11, 12, 13]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Consecutive elements grouping list
res = group_consecutive(test_list)
 
# printing result
print("Grouped list is : " + str(res))

Output
The original list is : [1, 2, 3, 6, 7, 8, 11, 12, 13]
Grouped list is : [(1, 3), (6, 8), (11, 13)]

Time complexity: O(n), where n is the length of the input list,
Auxiliary space: O(1).

Method 3: Using a for loop and a temporary list.

Use a for loop and a temporary list to group consecutive elements in the input list.




# initialize list
test_list = [1, 2, 3, 6, 7, 8, 11, 12, 13]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Consecutive elements grouping list
# using a for loop and a temporary list
res = []
temp = [test_list[0]]
for i in range(1, len(test_list)):
    if test_list[i] == test_list[i-1] + 1:
        temp.append(test_list[i])
    else:
        res.append((temp[0], temp[-1]))
        temp = [test_list[i]]
res.append((temp[0], temp[-1]))
 
# printing result
print("Grouped list is : " + str(res))

Output
The original list is : [1, 2, 3, 6, 7, 8, 11, 12, 13]
Grouped list is : [(1, 3), (6, 8), (11, 13)]

Time complexity: O(n), where n is the length of the input list. 
Auxiliary space: O(n), since it creates two lists: res and temp.

Method 4: Using itertools.groupby() and a list comprehension

This method uses itertools.groupby() to group consecutive elements together and then creates a list of tuples with the first and last element of each group using a list comprehension.




import itertools
 
test_list = [1, 2, 3, 6, 7, 8, 11, 12, 13]
 
# group consecutive elements using itertools.groupby()
groups = []
for k, g in itertools.groupby(enumerate(test_list), lambda x: x[0]-x[1]):
    groups.append(list(map(lambda x: x[1], g)))
 
# create a list of tuples with the first and last element of each group
res = [(group[0], group[-1]) for group in groups]
 
# print result
print("Grouped list is : " + str(res))

Output
Grouped list is : [(1, 3), (6, 8), (11, 13)]

Time complexity: O(n), where n is the length of the input list. 
Auxiliary space: O(n), where n is the length of the input list.

Method 5: Using numpy.diff() and numpy.split()

This method uses numpy’s diff() function to calculate the differences between consecutive elements of the input list. It then uses numpy’s split() function to split the list into subarrays where the differences are not equal to 1. Finally, it creates a list of tuples with the first and last element of each subarray.




import numpy as np
 
test_list = [1, 2, 3, 6, 7, 8, 11, 12, 13]
 
# calculate the differences between consecutive elements
diffs = np.diff(test_list)
 
# split the list into subarrays where the differences are not equal to 1
groups = np.split(test_list, np.where(diffs != 1)[0]+1)
 
# create a list of tuples with the first and last element of each group
res = [(group[0], group[-1]) for group in groups]
 
# print result
print("Grouped list is : " + str(res))

Output:

Grouped list is : [(1, 3), (6, 8), (11, 13)]

Time complexity: O(n), where n is the length of the input list. 
Auxiliary space: O(n), as it needs to create temporary arrays to store the differences and subarrays of the input list.


Article Tags :