How to convert a list to a set in Python

This tutorial is about how to convert a list to a set in Python. A set is an unordered collection of unique items. A list can have repeating elements but a set cannot have repeating elements.

If you want to learn more about Python Programming, visit Python Programming Tutorials.

We can convert a list to a set in three ways

  • Using Set() Function.
  • Using Custom Function.
  • Using Dict Function

Using set() Function to convert a list to a set

This is one of the methods to convert a list into a set. We have used the set() constructor and passed the list as an argument.

#Code starts here

list = ['Joe', 'Jen', 'John']
 
#convert the list using set
s = set(list)
 
#display the set
print(s)

#Code ends here

Using Custom Function for conversion of a list to a set

#Code starts here

def conversion(list):

    s = set()

    for x in list:

        s.add(x)

    return s

Names = ['John', 'Joe', 'Jane', 'Harry', 'Leo']

n = conversion (Names)

print(n)

#Code ends here

Using Dictionary function

#Code Starts Here

list_1 = ['John', 'John', 'Ana', 2, 2, 3, 4]

x = list(dict.fromkeys(list_1))

s = set(x)

print(s)

Let us know your valuable feedback.

Leave a Comment

Your email address will not be published. Required fields are marked *