Eliminating duplicates from a list using a single code of line in Python

Hey Coder! In this article, we are going to learn how to eliminate the duplicate elements of a list using a single line of code in Python.

We are going to use one of the properties of the set data type in Python.

Sets in Python

A set is an unordered collection with no duplicate elements. One of the basic use of set is to eliminate duplicate entries. We use curly braces {} to represent a set and can also use the function set() to declare a set object.

Also, set objects are immutable.

We cannot declare an empty set using {}, as the interpreter understands it as a dictionary object. So we use the function set() to declare an empty set.

We can also use the function set() to convert a list or tuple into a set that usually contains distinct elements.

If we compare dictionaries and sets, we will find that both of them are identical but not the same. One of the differences we can find between a set and a dictionary is that set is that dictionaries consist of a set of key and value pairs, whereas a set only consists of unique keys.

Even if we declare a set with repeated elements, they automatically get eliminated from the set. We are going to use the same concept in our program to implement the elimination of duplicates of a list and tuples.

Program

Let us first declare a list list1 of some elements with some repeated elements.

Now, print the list1.

```list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 5, 3, 1, 'hi', 'hello', 'hi']
print(list1)```

Now, let us use the set() method to convert the list1 into a set. The set automatically eliminates the duplicates. We make use of the list() function to convert the set object to list again and store it in the variable called list2.

Also, print list2.

```list2 = list(set(list1))
print(list2)```

The above line list2 = list(set(list1)) does the whole work.

Output :

```[1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 5, 3, 1, 'hi', 'hello', 'hi']
[1, 2, 3, 4, 5, 6, 7, 8, 9, 'hi', 'hello']

```

In the output, we can notice that all the duplicates in list1 are eliminated.

Hurrah! In this article, we have learned to eliminate the duplicates using a single line of code in python.

Thank you for reading the article. I hope this helped you in some way. Also do check out some other related articles to the topic below: