The goal: remove any duplicates from a sorted list.
Example: given the list
[2, 2, 4, 5, 5] we want to get the result:
[2, 4, 5]
One way to remove duplicates from a list is using
set this way:
Note that we will get back a set. To get a list, we can convert the set back to a list:
New list comparison
We can create another empty list and check whether an item from the original list is in the new list.
We will add the item to the new list only if it’s already there. This way is quite popular as it can also be applied in other languages (as opposed to the
This can also be done in a form of list comprehension:
In the previous solution we used a new list. Let’s see how to achieve the same result with in-place modification of the list we have:
There is a way to get a list without duplicates using
Personally, I don’t see a particular reason to use this way but nonetheless, it’s another way out there so let’s see how it’s done