Thursday, December 26, 2024
Google search engine
HomeLanguagesPython | Convert set into a list

Python | Convert set into a list

Given a set, write a Python program to convert the given set into a list.

Input : ('Geeks', 'for', 'Lazyroar')
Output : ['Geeks', 'for', 'Lazyroar']
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




# set into a list
my_set = {'Geeks', 'for', 'Lazyroar'}
print(type(my_set))
 
s = list(my_set)
print(type(s))


Output

['Geeks', 'for', 'Lazyroar']

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




# convert a set into a list
def convert(set):
    return sorted(set)
 
# Driver function
my_set = {1, 2, 3}
 
s = set(my_set)
print(convert(s))


Output

[1, 2, 3]

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




# program to convert a  set into a list
def convert(s):
    return list(map(lambda x: x, s))
# Driver function
s = {1, 2, 3}
print(convert(s))


Output

[1, 2, 3]

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):
    # Use a list comprehension to create a new list from the elements in the set
    return [elem for elem in s]
 
s = {1, 2, 3}
print(convert(s))


Output

[1, 2, 3]

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




#program to convert a  set into a list
def convert(set):
    return [*set, ]
 
# Driver function
s = set({1, 2, 3})
print(convert(s))


Output

[1, 2, 3]

Time complexity: O(n)
Auxiliary Space: O(n)

RELATED ARTICLES

Most Popular

Recent Comments