Python | Consecutive duplicates all elements deletion in list

Sometimes, while working with Python list, a problem can occur to filter list to remove duplicates. The solution to this has been discussed before. But sometimes, we may have a problem in which we need to delete the duplicate and element itself if it occurs more than 1 in consecution. This type of problem can occur in day-day programming and other applications as well. Let’s discuss a shorthand in which this task can be performed.

Method : Using list comprehension + groupby() + sum()
This task can be performed using the combination of above functions. The first step is grouping the elements into duplicates using groupby(), and then if they occur more than 0 times, remove them, i.e include only those elements that occur once. This counting task is handled by sum()

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Consecutive duplicates all elements deletion in list
# using list comprehension + sum() + groupby()
from itertools import groupby
  
# initialize list
test_list = [1, 1, 3, 4, 4, 4, 5, 6, 6, 7, 8, 8, 6]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Consecutive duplicates all elements deletion in list
# using list comprehension + sum() + groupby()
res = [i for i, j in groupby(test_list) if sum(1 for x in j) < 2]
  
# printing result
print("List after consecutive duplicates elements deletion : " + str(res))

chevron_right


Output :

The original list is : [1, 1, 3, 4, 4, 4, 5, 6, 6, 7, 8, 8, 6]
List after consecutive duplicates elements deletion : [3, 5, 7, 6]


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.