In Python, we generally wish to remove the duplicate elements, but sometimes for several specific usecases, we require to have remove just the elements repeated in succession. This is a quite easy task and having a shorthand for it can be useful. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using
groupby() + list comprehension
Using the groupby function, we can group the together occurring elements as one and can remove all the duplicates in succession and just let one element be in the list.
The original list is : [1, 4, 4, 4, 5, 6, 7, 4, 3, 3, 9] The list after removing consecutive duplicates : [1, 4, 5, 6, 7, 4, 3, 9]
Method #2 : Using
zip_longest() + list comprehension
This function can be used to keep the element and delete the successive elements with the use of slicing. The zip_longest function does the task of getting the values together in the one list.
The original list is : [1, 4, 4, 4, 5, 6, 7, 4, 3, 3, 9] List after removing consecutive duplicates : [1, 4, 5, 6, 7, 4, 3, 9]
- Python groupby method to remove all consecutive duplicates
- Python - Remove alternate consecutive duplicates
- Python | Consecutive duplicates all elements deletion in list
- Python - Ways to print longest consecutive list without considering duplicates element
- Python Remove Duplicates from a List
- Python - Ways to remove duplicates from list
- Python | Remove all duplicates and permutations in nested list
- Python | Remove duplicates from nested list
- Python | Sort given list by frequency and remove duplicates
- Python | Remove duplicates based on Kth element tuple list
- Python | Merging duplicates to list of list
- Remove all duplicates from a given string in Python
- Python | Remove all duplicates words from a given sentence
- Python | Remove duplicates in Matrix
- Python - Remove Equilength and Equisum Tuple Duplicates
- Python - Remove Kth Index Duplicates in Tuple
- Python - Remove K length Duplicates from String
- Python | Program to print duplicates from a list of integers
- Python | Program to count duplicates in a list of tuples
- Python | Combine two lists by maintaining duplicates in first list
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.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.