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() + groupby()
This task can be performed using the combination of above functions in which we can group the elements in breaks calculated using lambda function by finding difference between the index and value in list. The map() is used to combine the logic and itemgetter ensures the grouping is on value. Works with Python2 only.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to demonstrate working of
# Group elements on break positions in list
# using itemgetter() + map() + lambda() + groupby()
from itertools import groupby
from operator import itemgetter
  
# initialize list
test_list = [1, 2, 4, 5, 6, 8, 9, 11]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Group elements on break positions in list
# using itemgetter() + map() + lambda() + groupby()
res = list(map(itemgetter(1), j) for i, j in 
           groupby(enumerate(test_list), lambda (x, y) : x - y))
  
# printing result
print("Grouping of elements at breaks : " + str(res))

chevron_right


Output :

The original list is : [1, 2, 4, 5, 6, 8, 9, 11]
Grouping of elements at breaks : [[1, 2], [4, 5, 6], [8, 9], [11]]


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.