55. Problem to pack consecutive duplicates of given list.

In this Python list program, we will take a user input as a list and pack consecutive duplicates of given list elements into sublists with the help of the below-given steps.

Pack consecutive duplicates in the list:

Steps to solve the program
  1. Take a list of consecutive duplicate elements as input.
  2. Import groupby from itertools.
  3. Create a new list using list comprehension to pack consecutive duplicates elements into sublists using groupby.
  4. Print the list to see the output.
				
					#Input list
list1 = [0, 0, 1, 2, 3, 4, 4, 5, 6, 6, 7, 8, 8, 9]
from itertools import groupby

#Creating new list
list2 = [list(group) for key, group in groupby(list1)]

#Printing output
print(list2)
				
			

Output :

				
					[[0, 0], [1], [2], [3], [4, 4], [5], [6, 6], [7], [8, 8], [9]]
				
			

Related Articles

Remove consecutive duplicates of given lists

Split a given list into two parts

Leave a Comment