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
- Take a list of consecutive duplicate elements as input.
- Import groupby from itertools.
- Create a new list using list comprehension to pack consecutive duplicates elements into sublists using groupby.
- 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
Python program to insert items at a specific position in the list.
Python program to select random numbers from the list.
Python program to create a 3*3 grid with numbers.
Python program to zip two lists of lists into a list.
Python program to convert the first and last letter of each item from Upper case and lowercase.