Python | Identical sequential grouping in the list

Method: Using groupby () + list comprehension
This task can be easily accomplished with the built-in groupby () function offered by Python. It might have to do with list comprehension for logical combination and iteration.

# Python3 code to demonstrate how it works
# Identical sequential grouping in the list
# using groupby () + list comprehension

from itertools import groupby

 
# initialize list

test_list = [ 4 , 4 , 5 , 5 , 5 , 7 , 7 , 8 , 8 , 8 ]

 
# print the original list

print ( "The original list is:" + str (test_list))

 
# Identical sequential grouping in the list
# using groupby () + list comprehension

res = [ list (y) for x, y in groupby (test_list)]

  
# print 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]] 




Get Solution for free from DataCamp guru