How To Remove duplicates in a list - Python

In this article you'll learn how to remove duplicate values in a python list.


  


# x is a list that contains many duplicates
x = [12, 2, 5, 65, 2, 9, 5, 2, 9, 12]
# a variable that'll hold the unique values
uniques = []

# loop through all the lists checking to make sure
# that a specific value is not present in uniques variable,
# if not append the value otherwise continue looping through
for i in x:
    if i not in uniques:
        uniques.append(i)

print(f"Duplicate list: {x}")
print(f"Unique values: {uniques}")

You can see how easy that was, we just define two varaibles, the 1st one we set it to a list that has many duplicates, and the 2nd one, we use it to store the List of unique values in x. Then we use for loop, to check all the values, if a specific value is not in the varaible uniques then we append the value.