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()
# 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)) |
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]
Recommended Posts:
- Python | Remove consecutive duplicates from list
- Python | Consecutive remaining elements in list
- Python | Consecutive elements grouping in list
- Python | Consecutive elements pairing in list
- Python | Group consecutive list elements with tolerance
- Python groupby method to remove all consecutive duplicates
- Python | Column deletion from list of lists
- Python | Front and rear range deletion in a list
- Python | Merging duplicates to list of list
- Python | Remove Duplicates from a List
- Python | Ways to remove duplicates from list
- Python | Remove duplicates from nested list
- Python | Program to count duplicates in a list of tuples
- Python | Sort given list by frequency and remove duplicates
- Python | Program to print duplicates from a list of integers
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.



