How to Create a Set From a List in Python

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

Output

{‘Shyam’, 10, 13.2, ‘Feroz’, ‘Bilal’, ‘Ram’}

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

Output

{‘Feroz’, 10, 13.2, ‘Ram’, ‘Shyam’, ‘Bilal’}

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

Output

{‘Ram’, 10, 13.2, ‘Feroz’, ‘Bilal’, ‘Shyam’}

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

Leave a comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.