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
Python Tutorial | Learn Python Programming Language
Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers
Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts
Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced
Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions
Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs
Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Enumerate() in Python
enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read
Python Data Types
Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Python Introduction
Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Input and Output in Python
Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read