In this tutorial, I will be sharing how to convert list to set in python. As we know set does not allow duplicates i.e contains only unique elements without any order. Our main goal should be to remove all the duplicates present in the given list.
Related Articles
Note: We will use python set() method to convert list to set.
Example of Converting list to set in Python
1. Converting list of String to set in Python Example
Below is the python program to convert list of String to set.
listOfCountries = ['India', 'USA', 'Canada', 'NewZealand', 'India', 'USA']
print("Given list of Countries: ", listOfCountries)
uniqueCountries = set(listOfCountries)
print("Set of unique countries: ", uniqueCountries)
Output:
Given list of Countries: ['India', 'USA', 'Canada', 'NewZealand', 'India', 'USA']
Set of unique countries: {'NewZealand', 'India', 'USA', 'Canada'}
2. Converting list of Numbers to set in Python Example
Below is the python program to convert list of Numbers to set.
listOfNumbers = [12, 15, 55, 8, 32, 15, 55, 8]
print("Given list of Numbers: ", listOfNumbers)
setOfUniqueNumbers = set(listOfNumbers)
print("Set of numbers: ", setOfUniqueNumbers)
Output:
Given list of Numbers: [12, 15, 55, 8, 32, 15, 55, 8]
Set of numbers: {32, 8, 12, 15, 55}
That's all for today, please mention in comments in case you have any questions related to converting list to set in python.