This post will discuss how to remove duplicates from a list in Python while preserving the original order of elements.

If ordering information is not required, we can simply use a set that doesn’t allow duplicates. This removes duplicates, but the original order of elements is not maintained as sets are the unordered collection.

Download  Run Code

 
As evident from the above example, the original order of items is lost. This post provides an overview of some of the available alternatives to preserve the original order of items.

1. Using OrderedDict object

To keep the ordering information, we can use OrderedDict from Python collections module. The OrderedDict is a subclass of dict that remembers the insertion order of its entries.

Download  Run Code

 
Alternatively, we can take advantage of the fact that the original insertion position remains unchanged when a new entry overwrites an existing entry of an OrderedDict. Here is an example:

Download  Run Code

2. Using a Dictionary

Starting from Python 3.7, we can use a regular dictionary to remove duplicates from a list, as they are guaranteed to be ordered. The idea is to use the items of the original list as keys of the dictionary, and assign any value to them (such as True or None). Then we can get the keys of the dictionary as a list using the list() function and the keys() function. Here is an example of how to implement this method:

Download  Run Code

3. Using more_itertools Library

Python’s more-itertools library provides elegant routines for working with Python iterables. It has a unique_everseen function that yields unique elements while preserving order. Following is a simple example demonstrating usage of this function:

Download Code

4. Using List Comprehension

Another approach is to construct a “new list” from the original list using list comprehensions. The idea is to iterate over the original list, and append each item to the new list only if it is not already in the new list. Here is an example of how to implement this method:

Download  Run Code

 
Note this approach is relatively slower than the above two approaches. We can also use a dictionary as a helper data structure.

Download  Run Code

That’s all about removing duplicates from a list in Python.