Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Python | Identical Consecutive Grouping in list

  • Last Updated : 09 Sep, 2019

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.




# 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))
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
Recommended Articles
Page :

Start Your Coding Journey Now!