List to set Python
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']
Typecasting to list can be done by simply using list(set_name).
# Python3 program to convert a
# set into a list
my_set = {'Geeks', 'for', 'geeks'}
s = list(my_set)
print(s)
Output: ['Geeks', 'for', 'geeks']
# 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))
Output:
[1, 2, 3]
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.
# 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))
Output:
[1, 2, 3]
# 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]
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics. To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning Basic Level Course
Article Tags :
Python Python Programs
Python list-programs Python set-programs |