Python Convert List to Set

In Python, a set is an unordered collection of unique items. To convert a list to a set, use the native Python set() function and store the result in a variable. Any duplicate element values from the original list will be removed.

 

Python List to Set Example

In the example below, we will convert a list of numbers with duplicate values to a set of unique ones.

 

numbers = [4, 6, 9, 4, 2]

result = set(numbers)

print(result)
print(type(result))
{9, 2, 4, 6}
<class 'set'>

 

Here is another example, this time converting a list of strings to a set.

 

names = ['Ben', 'Emma', 'john', 'Ben']

result = set(names)

print(result)
{'Ben', 'john', 'Emma'}

 

Read more about how to use Python sets.