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.
# Python3 code to demonstrate working of# Identical Consecutive Grouping in list# using groupby() + list comprehensionfrom itertools import groupby # initialize listtest_list = [4, 4, 5, 5, 5, 7, 7, 8, 8, 8] # printing original listprint("The original list is : " + str(test_list)) # Identical Consecutive Grouping in list# using groupby() + list comprehensionres = [list(y) for x, y in groupby(test_list)] # printing resultprint("List after grouping is : " + str(res)) |
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]]
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course


