Remove duplicates using Python set() function
A list may contain duplicate elements, using the sets these duplicate values can be remove in Python. As we know that it is an unordered data structure that keeps only unique elements in the list. For example a list having duplicate elements.
List [5, 3, 45, 6, 5, 7, 2, 10, 45, 8, 5].
using the said list we create a set with this list. Duplicate elements will be suppressed and only unique elements added to final list.
# Convert list to set and then back to a list NumsList = list(set(NumsList)) print NumsList
This produces a list of elements, but the order of list changed.
[2, 3, 5, 6, 7, 8, 10, 45]
Retain the order after removing duplicates
Using the set method unique elements is arranged but the order is lost.
List with duplicate values [2, 4, 10, 20, 5, 2, 20, 4]
To delete the duplicate values from the list and keeping the order as it is.
# Python code to remove duplicate elements def Dup_remov(duplicate): unique_list =  for num in duplicate: if num not in unique_list: unique_list.append(num) return unique_list # Driver Code duplicate = [2, 4, 10, 20, 5, 2, 20, 4] print(Dup_remov(duplicate))
[2, 4, 10, 20, 5]