/  Technology   /  Removing duplicates in lists in python Part-II
Removing duplicates in lists Part-1

Removing duplicates in lists in python Part-II

In this article, which is in continuation with the previous article, we’ll discuss the rest of the ways, specifically some built-in functions using which we can make a unique list by removing all the duplicates present in it. Make sure you refer to the first part before we move on to learn the other methods.

  • Using set()
  • Using dict.fromkeys()

 

Using set():

A set is a data structure which is both unordered and unindexed. They store collections of unique items separated by commas enclosed within parentheses. Sets won’t store duplicate values, unlike lists.

As we know, sets cannot store duplicate items, we’ll convert our list to a set to remove the duplicates and then convert it back to a list using list().

Example:

original_list = [1,3,5,7,1,3,5,9,11]
print ("original list is : " + str(original_list))

unique_list = list (set(original_list))

print("List after removing duplicates : " + str(unique_list))

output:

 

Using dict.fromkeys():

fromkeys() is a built-in function that generates a dictionary from the keys we have passed to it. As we know dictionaries cannot have duplicate keys, this function removes any duplicates from our list. We then convert this dictionary back to a list using the list() function.

Example:

original_list = [1,3,5,7,1,3,5,9,11]
print ("original list is : " + str(original_list))

unique_list = list (dict.fromkeys(original_list))

print("List after removing duplicates : " + str(unique_list))

output:

Leave a comment