Python Set To List

python-set-to-list-ipcisco-1

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:

 

  • By List Method
  • Bu Sorted Method

 

Now let’s learn each of these methods that convert Python sets to lists and reverse.

 


You can check also Python Set Function


 

By Python List Method

 

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


 

python-set-to-list-ipcisco-1

 

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'}

 

python-list-to-set-ipcisco-2

 

And this time as above, the output will be a set.

 


 

By Python Sorted Method

 

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']

 

python-set-to-list-ipcisco-3.jpg

 

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.

Back to: Python Programming Course > Python Sets

Leave a Reply

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

Python Programming Course

Collapse
Expand
Latest Blog Posts