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 : 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

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


Output :

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


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.