Last Updated on May 12, 2024 by Roshan Parihar
To create a set from a list in Python, use the set()
function that takes an argument as the list variable to convert to a set variable.
You can also use an asterisk (*) for converting a set to a list. Let’s find out with the examples given below.
Create a Set From a List Using set() Function in Python
If you want to create a set from the list, you have to use the set()
function in Python. The function is pre-defined in Python and takes a single argument as the list variable.
Example 1
1 2 3 4 5 6 7 8 |
#declare list in Python myList = ['Ram', 'Shyam', 10, 'Bilal', 13.2, 'Feroz']; #Create Set from List using set() in Python mySet = set(myList) #Print the result print(mySet) |
Output
The above example shows the converted list variable to a set variable. However, the sequence of items is not defined in the variable as a set is an unordered collection of elements. So, you cannot set the sequence of elements on conversion.
You can check the sequence of items in the list and set variables. The sequences are different on both variables.
Using add(), set(), and for loop to Convert List to Set in Python
The for loop with add()
and set()
functions are useful to convert a list variable to a set in Python.
Firstly, it requires defining a set variable using the set()
of Python. After that, use the add()
function with a for loop to add elements of the list one by one to a set.
Example 2
1 2 3 4 5 6 7 8 9 10 |
#declare list in Python myList = ['Ram', 'Shyam', 10, 'Bilal', 13.2, 'Feroz']; #Create Set from List using add(), set(), and for loop in Python mySet = set() for x in myList: mySet.add(x) #Print the result print(mySet) |
Output
The above example requires more coding to write and create a set variable from the list. The resulting output gives the set variable. However, the sequence is still not defined as a set variable is a collection of unordered elements.
Using Asterisk (*) Sign
In addition to the above methods, you can also use the asterisk (*) sign to construct a set from the list variable in Python.
Example 3
1 2 3 4 5 6 7 8 |
#declare list in Python myList = ['Ram', 'Shyam', 10, 'Bilal', 13.2, 'Feroz']; #Create Set from List using for loop in Python mySet = {*myList} #Print the result print(mySet) |
Output
The above example contains the output with set elements taken from the list elements.
The most noteworthy thing here is that all the above methods give different results on conversion. Each method gives a different sequence as compared to one another.
You May Also Like to Read