Python has different data types in it. A set is also one of the data types in python. A set is generally defined as an unordered collection of values with no duplication. The concept of the set can be used to avoid duplications. For example, let’s say membership or login applications. In python, you can easily convert one datatype into another one. Now, let’s look at the python set to list conversion.

There are some things you should keep in mind before using sets in python. You can use the set() function to create a set in python. If you want to create an empty set, you should use set() brackets. If you use curly braces ‘{}’ then it will become a dictionary in python.

## Basic set operations in python

Before going to type conversions, let’s shed some light on basic set operations in python. Trust me, it wont take more than 5 minutes.

Let’s start by creating a simple set in python.

#Creating two sets
A  = set('hackanons')
B  = set('python')

#Prints letter in both A and B
print(A & B)
#Prints letters in both A or B or both
print(A | B)
#Prints letters in A but not in B
print(A - B)
#Prints letters in A or B but not in both
print(A ^ B)
{'n', 'h', 'o'}
{'a', 'h', 'c', 'y', 'p', 'n', 's', 't', 'k', 'o'}
{'a', 's', 'c', 'k'}
{'a', 'c', 'y', 'p', 's', 't', 'k'}

I hope by now you got better of sets and it’s operation basics in python.

## Python set to list conversion

Python allows the conversion of one datatype into another. But you have to pay a bit more attention in the process.

Let’s start by creating a set and then we can convert it into a list using list() function.

#Create a list
set_a = {'I','Love','Python'}

#Convert set into list
my_list = list(set_a)

#Print list
my_list
['Love', 'I', 'Python']
• Here, we have created a set.
• Then, we have converted into a list using list() function.
• Then we have printed the list. Our list is ready now.

## Set to list conversion using sorted() function

You can even use the sorted() function to convert a set into a sorted list. Let’s see how it works.

#Create a list
set_a = {'I','Love','Python'}

#Convert set into list
my_list = sorted(set_a)

#Print list
my_list
['I', 'Love', 'Python']

I am using the same example to keep things simple. You can see how the sorted() function returns a list from a set. That’s it.

## Wrapping Up

You can convert one data type into another in python. In this case, we have converted a set into a python list using the list() function. Similarly, you can do it using the sorted() function as well as shown above. That’s all for now. Happy Python!!!.

Categorized in:

Tagged in: