Converting a Set into a List in Python
In this tutorial, we will learn how to convert a set into a list in Python.
A set in Python is an unordered sequence without duplicate elements.
Searching of elements is very fast is set as compared to the list.
Let’s create a sample set and add some elements.
Create a Set in Python:
# example 1
set_1 = { 1, 2, 3 }
print (type(set_1))
print (set_1)
print("\n")
# example 2
set_2 = {4, 7, 8}
set_2.add(3)
print (set_2)Output :
<class 'set'>
{1, 2, 3}
{8, 3, 4, 7}After, creating the set it’s time to create a list from the above set.
Convert a set into a list in Python
Certainly, a list has more flexibility than sets thereby there is a need for conversion.
Method 1:
list ( sequence )
set_sample = { 4, "hello" , 9 , 8.9 }
set_list = list (set_sample)
print (set_list) # prints in any order no specific orderOutput : [8.9, 9, 'hello', 4]
Method 2 :
sorted ( sequence ) returns a list with the sorted list from the elements in the set.
Here, the sequence must contain valid items that can be sorted.
set_sample = { 4, 9 , 8.9 , 1 , 67, 32 }
set_list = sorted (set_sample) # converts the above set into list
print (set_list)
print (type(set_list))Output : [1, 4, 8.9, 9, 32, 67] <class 'list'>
These are some of the conventional ways to convert or create list from a set in Python.
You may also read:
Leave a Reply