In this Python list program, we will take a user input as a list and remove consecutive duplicates of given lists with the help of the bewlo-given steps.
Remove consecutive duplicates in a list:
Steps to solve the program
- Take a list having consecutive duplicate elements as input.
- Create an empty list to store the elements after we remove consecutive duplicates in the list.
- Import groupby from itertools to groupby elements from the given list.
- Add an element with 0 indexes after applying groupby to each element to the empty list after each iteration.
- Print the list to see the output.
#Input list
list1 = [0, 0, 1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 8, 9, 4, 4]
#Creating empty list
list2 = []
from itertools import groupby
for value in groupby(list1):
list2.append(value[0])
#Printing output
print(list2)
Output :
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 4]
Related Articles
Python program to pack consecutive duplicates of given list elements into sublists.
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.