In Python Programming, sometimes we convert some data types to others. Python set to list convertion is one of them. We convert sets to list in different ways in python. In this lesson, we will see these methods. So what are these methods that convert sets to lists? These are:
Now let’s learn each of these methods that convert Python sets to lists and reverse.
You can check also Python Set Function
Table of Contents
In the below example, we will give firstly an example for list method.
dwarves1 = {"Thorin", "Balin", "Dwalin"}
print(list(dwarves1))
The output of this python code will be a list like below:
['Dwalin', 'Balin', 'Thorin']
You can also check Python Set Operations
The reverese of this method is also true. We can convert a python list to a python set with the help of set method. Below, the same example will be showed as reverse of above code.
dwarves2 =['Dwalin', 'Balin', 'Thorin']
print(set(dwarves2))
{'Balin', 'Thorin', 'Dwalin'}
And this time as above, the output will be a set.
We can also use python sortend method to convert a set to a list. When we use sorted method on a set, it is converted to a list.
In the below example, we will do this change.
dwarves1 = {"Thorin", "Balin", "Dwalin"}
print(sorted(dwarves1))
The output of the code will be like below:
['Balin', 'Dwalin', 'Thorin']
In this lesson, we have learned two methods that are used to convert python set to list. You can create different examples on this lesson.
Leave a Reply