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
# 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.
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
# 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))
OutputThe 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
# 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))
OutputThe 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]
# 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))
OutputGrouped 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]
# 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.
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 | 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']Output:
3 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
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
Remove Last Element from List in Python
Given a list, the task is to remove the last element present in the list. For Example, given a input list [1, 2, 3, 4, 5] then output should be [1, 2, 3, 4]. Different methods to remove last element from a list in python are:Using pop() methodUsing Slicing TechniqueUsing del OperatorUsing Unpacking
2 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
Python - Count the elements in a list until an element is a Tuple
The problem involves a list of elements, we need to count how many elements appear before the first occurrence of a tuple. If no tuple is found in the list, return the total number of elements in the list. To solve this, initialize a counter and use a while loop to iterate through the list, checking
2 min read
Average of Each N-length Consecutive Segment in a List - Python
The task is to compute the average of each n-length consecutive segment from a given list. For example, if the input list is [1, 2, 3, 4, 5, 6] and n = 2, the output should be [1.5, 2.5, 3.5, 4.5, 5.5]. Let's discuss various ways in this can be achieved.Using List ComprehensionThis method uses list
3 min read