Related Articles

Python | Consecutive duplicates all elements deletion in list

• Last Updated : 05 Sep, 2019

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()`

 `# 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))`
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]
```

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up