Python | Identical Consecutive Grouping in list

Sometimes, while working with Python list we can have problem in which we need to perform grouping. There can be a particular problem in which we need to group consecutive occurring elements. Having solution to this problem is useful. Let’s discuss certain way in which this can be done.

Method : Using groupby() + list comprehension
This task can be performed using the inbuilt groupby() offered by Python in easy way. This can be coupled with list comprehension for logic combination and iteration.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Identical Consecutive Grouping in list
# using groupby() + list comprehension
from itertools import groupby
  
# initialize list
test_list = [4, 4, 5, 5, 5, 7, 7, 8, 8, 8]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Identical Consecutive Grouping in list
# using groupby() + list comprehension
res = [list(y) for x, y in groupby(test_list)]
  
# printing result
print("List after grouping is : " + str(res))

chevron_right


Output :

The original list is : [4, 4, 5, 5, 5, 7, 7, 8, 8, 8]
List after grouping is : [[4, 4], [5, 5, 5], [7, 7], [8, 8, 8]]


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.