Python | Convert set into a list

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

Examples:

Input : {1, 2, 3, 4}
Output : [1, 2, 3, 4]

Input : {'Geeks', 'for', 'geeks'}
Output : ['Geeks', 'for', 'geeks']

 
Appraoch #1 : Using list(set_name).

Typecasting to list can be done by simply using list(set_name).

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to convert a 
# set into a list
my_set = {'Geeks', 'for', 'geeks'}
  
s = list(my_set)
print(s)

chevron_right


Output:



['Geeks', 'for', 'geeks']

 

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

[1, 2, 3]

 
Appraoch #2 : using sorted() method

Using sorted() function will convert the set into list in a defined order. The only drawback of this method is that the elements of the set need to be sortable.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to 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))

chevron_right


Output:

[1, 2, 3]

 
Appraoch #3 : 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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

[1, 2, 3]


My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.