Given a set, write a Python program to convert the given set into a list.
Input : ('Geeks', 'for', 'geeks')
Output : ['Geeks', 'for', 'geeks']
Explanation: The data type of the input is set <class 'set'> and
the data type of the output is list <class 'list'>.
Convert the set into a List
Below are the methods that we will cover in this article:
Convert Set to List using the list Method
Here we pass the set datatype inside the list parentheses as a parameter and this will convert the set data type into a list data type as shown in the code below.
Python3
my_set = { 'Geeks' , 'for' , 'geeks' }
print ( type (my_set))
s = list (my_set)
print ( type (s))
|
Output['Geeks', 'for', 'geeks']
Time complexity: O(n)
Auxiliary Space: O(n)
Set into a List using the sorted() method
Using the sorted() function will convert the set into a list in a defined order. The only drawback of this method is that the elements of the set need to be sortable.
Python3
def convert( set ):
return sorted ( set )
my_set = { 1 , 2 , 3 }
s = set (my_set)
print (convert(s))
|
Time complexity: O(n)
Auxiliary Space: O(n)
Convert the set into a list using the map() function
You can use the map() function to convert the set to a list by passing the set as an argument to the map() function and returning a list of the results. For example:
Python3
def convert(s):
return list ( map ( lambda x: x, s))
s = { 1 , 2 , 3 }
print (convert(s))
|
Time complexity: O(n)
Auxiliary Space: O(n)
Convert Set to List using List Comprehension
You can use list comprehension to create a new list from the elements in the set as shown in the code below.
Python3
def convert(s):
return [elem for elem in s]
s = { 1 , 2 , 3 }
print (convert(s))
|
Time complexity: O(n)
Auxiliary Space: O(n)
Convert Set into a List using [*set, ]
This essentially unpacks the set s inside a list literal which is created due to the presence of the single comma (, ). This approach is a bit faster but suffers from readability.
For example:
Python3
def convert( set ):
return [ * set , ]
s = set ({ 1 , 2 , 3 })
print (convert(s))
|
Time complexity: O(n)
Auxiliary Space: O(n)