Python Program to Remove Duplicate Element From a List

To understand this example, you should have the knowledge of the following Python programming topics:


Example 1: Using set()

list_1 = [1, 2, 1, 4, 6]

print(list(set(list_1)))

Output

[1, 2, 4, 6]

In the above example, we first convert the list into a set, then we again convert it into a list. Set cannot have a duplicate item in it, so set() keeps only an instance of the item.


Example 2: Remove the items that are duplicated in two lists

list_1 = [1, 2, 1, 4, 6]
list_2 = [7, 8, 2, 1]

print(list(set(list_1) ^ set(list_2)))

Output

[4, 6, 7, 8]

In the above example, the items that are present in both lists are removed.

  • Firstly, both lists are converted to two sets to remove the duplicate items from each list.
  • Then, ^ gets the symmetric difference of two lists (excludes the overlapping elements of two sets).

Also Read:

Before we wrap up, let's put your understanding of this example to the test! Can you solve the following challenge?

Challenge:

Write a function to remove duplicate elements from a list.

  • Return the list without any duplicate elements sorted in ascending order.
  • For example, for input [1, 2, 2, 3, 4, 4], the output should be [1, 2, 3, 4].
Did you find this article helpful?

Your builder path starts here. Builders don't just know how to code, they create solutions that matter.

Escape tutorial hell and ship real projects.

Try Programiz PRO
  • Real-World Projects
  • On-Demand Learning
  • AI Mentor
  • Builder Community