This tutorial will discuss how to remove consecutive duplicates in a Python list.
Suppose we have a list of numbers and we aim to remove consecutive duplicate values.
sampleList = [ 22, 33, 33, 55, 55, 55, 65, 77, 77, 33, 55]
For instance, in our list, we might encounter two consecutive 33s, followed by three consecutive 55s, and then two consecutive 77s. Our goal is to eliminate only the consecutive duplicates; non-consecutive duplicates should remain untouched.
To achieve this, we’ve designed a specific function.
def removeConsecutiveDuplicates(listObj): # List to store result without consecutive duplicates resultList = [] for i in range(len(listObj)): # Add item to resultList if it's the last item or not equal to the next item print(listObj[i]) if i == len(listObj) - 1 or listObj[i] != listObj[i+1]: resultList.append(listObj[i]) return resultList
This function accepts the list as its sole argument. It then iterates over the list by index position, comparing the element at index i with the element at index i+1. If they are identical, the function retains only one of the duplicates in the resulting list, effectively removing the consecutive duplicate. However, if duplicate elements are not in consecutive positions, they are preserved.
Here’s an example demonstrating how this function effectively removes consecutive duplicate elements from a list.
Let’s see the complete example,
Frequently Asked:
def removeConsecutiveDuplicates(listObj): # List to store result without consecutive duplicates resultList = [] for i in range(len(listObj)): # Add item to resultList if it's the last item or not equal to the next item print(listObj[i]) if i == len(listObj) - 1 or listObj[i] != listObj[i+1]: resultList.append(listObj[i]) return resultList # A List of Numbers sampleList = [ 22, 33, 33, 55, 55, 55, 65, 77, 77, 33, 55] print("Original List:", sampleList) # Remove consecutive duplicates from list sampleList = removeConsecutiveDuplicates(sampleList) print("List after removing consecutive duplicates:") print(sampleList)
Output
Original List: [22, 33, 33, 55, 55, 55, 65, 77, 77, 33, 55] 22 33 33 55 55 55 65 77 77 33 55 List after removing consecutive duplicates: [22, 33, 55, 65, 77, 33, 55]
Summary
Today, we learned how to remove consecutive duplicates in a Python list.