Python | Consecutive elements grouping in list
Last Updated :
27 Mar, 2023
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
import itertools
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 ]
test_list = [ 1 , 2 , 3 , 6 , 7 , 8 , 11 , 12 , 13 ]
print ("The original list is : " + str (test_list))
res = list (groupc(test_list))
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.
Python3
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
test_list = [ 1 , 2 , 3 , 6 , 7 , 8 , 11 , 12 , 13 ]
print ( "The original list is : " + str (test_list))
res = group_consecutive(test_list)
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.
Python3
test_list = [ 1 , 2 , 3 , 6 , 7 , 8 , 11 , 12 , 13 ]
print ( "The original list is : " + str (test_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 ]))
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.
Python3
import itertools
test_list = [ 1 , 2 , 3 , 6 , 7 , 8 , 11 , 12 , 13 ]
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)))
res = [(group[ 0 ], group[ - 1 ]) for group in groups]
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.
Python3
import numpy as np
test_list = [ 1 , 2 , 3 , 6 , 7 , 8 , 11 , 12 , 13 ]
diffs = np.diff(test_list)
groups = np.split(test_list, np.where(diffs ! = 1 )[ 0 ] + 1 )
res = [(group[ 0 ], group[ - 1 ]) for group in groups]
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.
Similar Reads
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 | 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 | 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 | 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 | 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
How to Compare Adjacent Elements in a List in Python
To compare adjacent elements in a list, we iterate through the list and compare each element with the next one to check if consecutive elements are equal or meet specific conditions. Using the itertools.pairwise()This is an efficient way to iterate through adjacent pairs. It generates consecutive pa
3 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 - Accessing nth element from tuples in list
We are given tuples in list we need to access Nth elements from tuples. For example, we are having a list l = [(1, 2), (3, 4), (5, 6)] we need to access the Nth element from tuple suppose we need to access n=1 or 1st element from every tuple present inside list so that in this case the output should
2 min read
Python groupby method to remove all consecutive duplicates
In Python, the groupby method from the itertools module provides a powerful way to group consecutive identical elements in an iterable. This functionality can be effectively utilized to remove all consecutive duplicates from a sequence. By retaining only the first occurrence of each group of identic
4 min read
Access List Items in Python
Accessing elements of a list is a common operation and can be done using different techniques. Below, we explore these methods in order of efficiency and their use cases. Indexing is the simplest and most direct way to access specific items in a list. Every item in a list has an index starting from
2 min read