Easy Tutorial
❮ Python Os Openpty Python Os Remove ❯

Python Remove Duplicates from a List

Python3 Examples

In this section, we will learn how to remove duplicate elements from a list.

Key points include:

Example

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

print(list(set(list_1)))

Executing the above code outputs:

[1, 2, 4, 6]

In the above example, we first convert the list to a set and then back to a list. Sets cannot have duplicate elements, so set() removes duplicates.

Remove Duplicate Elements from Two Lists

In the following example, elements that exist in both lists will be removed.

Example

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

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

First, use set() to convert both lists into sets to remove duplicates. The ^ operator gets the symmetric difference of the two lists.

Executing the above code outputs:

[4, 6, 7, 8]

Python3 Examples

❮ Python Os Openpty Python Os Remove ❯