Python program to remove duplicates from a list

Learn multiple ways to remove duplicates from a list in Python.

Python program to remove duplicates from a list

Given a list of numbers in Python, the objective is to remove any possible duplicates in the list.

input 1 ==> [10, 20, 30, 30, 40, 60]
output 1 ==> [10, 20, 30, 40, 60]

input 2 ==> [10, 20, 30, 40, 50, 60, 30]
output 2 ==> [10, 20, 30, 40, 50, 60]

Method 1 - Using a for loop

Code

my_list = [10, 20, 30, 40, 50, 60, 30]

result_list = []

for i in my_list:
    if i not in result_list:
        result_list.append(i)
    else:
        continue

print(result_list)

Output

[10, 20, 30, 40, 50, 60]

Method 2 - Using sets

A set data type cannot store duplicates. So you can also use this method to remove duplicates from a list.

Be careful, the set() will change the order of the elements in the list.

Code

my_list = [10, 20, 30, 40, 50, 60, 30]

print(list(set(my_list)))

Output

[40, 10, 50, 20, 60, 30]

Subscribe to Pylenin

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe