To remove duplicates from a sorted array in Python without using extra space, we can define a function which will loop over your list and delete any duplicates.
def removeDuplicates(arr):
for i in range(len(arr)-1,0,-1):
if arr[i] == arr[i-1]:
del arr[i]
return arr
sorted_list = [1,2,2,3,3,4,5,5,8,8,8,8,9,9,9]
print(removeDuplicates(sorted_list))
#Output:
[1, 2, 3, 4, 5, 8, 9]
Another way to remove duplicates from a list is to convert it to a set and then back to a list.
sorted_list = [1,2,2,3,3,4,5,5,8,8,8,8,9,9,9]
print(list(set(sorted_list)))
#Output:
[1, 2, 3, 4, 5, 8, 9]
When working with collections in Python, a very common task to do is remove duplicates.
In Python, arrays are called lists, and we can easily delete all duplicate values from a sorted list with a loop which checks if the next element is the same as the current element and deletes it if they are the same.
This function removes the duplicates in place and doesn’t take any extra space.
Below is a function in Python which removes all duplicates from a sorted array.
def removeDuplicates(arr):
for i in range(len(arr)-1,0,-1):
if arr[i] == arr[i-1]:
del arr[i]
return arr
sorted_list = [1,2,2,3,3,4,5,5,8,8,8,8,9,9,9]
print(removeDuplicates(sorted_list))
#Output:
[1, 2, 3, 4, 5, 8, 9]
Removing Duplicates from List with set() in Python
A set is an unordered collection of unique elements. On the other hand, lists are ordered and can contain duplicates.
Converting a list to a set creates a new set with the same items as the list and removes all duplicates.
To remove duplicates from a list, we can use set() to convert a list to a set, and then use list() to convert it back.
This does take extra space but will sort and remove duplicates all in one step.
Below is how to remove duplicates from a list with the set() function in Python.
lst = [0,1,2,3,0,0,3]
print(list(set(lst)))
#Output:
[0,1,2,3]
Hopefully this article has been useful for you to learn how to remove duplicates from a sorted array in Python.