How to Create A Set From List Elements in Python

Last Updated on April 18, 2023 by Roshan Parihar

In this tutorial, learn how to create a set from list elements using Python. The short answer is to use the set() function of Python. It takes an argument as the list variable to convert to a set variable.

There are many other methods available that are useful to convert list variable to set in Python. Let’s find out with the useful examples given here.

Method 1: Using set() to Create A Set From List Elements in Python

To create a set from the list, you have to use the set() function in Python. The function is pre-defined in Python and uses to easily convert list variable to set. It takes a single argument as the list variable.

Output

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

The above example shows the converted list variable to 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.

Method 2: Using add(), set(), and for loop to Convert List to Set in Python

You can use the for loop with add() and set() to convert a list variable to set in Python. Firstly, it requires defining a set variable using the set() of Python. After that, use the add() function with for loop to add elements of the list one-by-one to set variable. See the example given below to see the method of for loop as given below:

Output

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

The above example requires more coding to write and create a set variable from list. The resulted output gives the set variable. However, the sequence is still not defined as a set variable is a collection of unordered elements.

Method 3: Using Asterick (*) Sign

In addition to the above methods, you can also use the asterisk (*) sign to construct a set from the list variable in Python. It requires to use the method as given below

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. However, the best method is to use the set() function of Python that requires less coding to write and create. But, you can try other methods also to get the required result in the output.

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.