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']
Approach #1 : Using list(set_name).
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) |
['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)) |
[1, 2, 3]
Approach #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.
# 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)) |
[1, 2, 3]
Approach #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.
# Python3 program to convert a # set into a list def convert(set): return [*set, ] # Driver function s = set({1, 2, 3}) print(convert(s)) |
[1, 2, 3]
Recommended Posts:
- Python | Convert mixed data types tuple list to string list
- Python | Convert list of string into sorted list of integer
- Python | Convert list of numerical string to list of Integers
- Python Program to convert List of Integer to List of String
- Python | Convert string List to Nested Character List
- Python | Convert list of string to list of list
- Python | Convert list of tuples to list of list
- Python | Convert list of tuples to list of strings
- Python - Convert List of Dictionaries to List of Lists
- Python - Convert list to Single Dictionary Key Value list
- Python - Convert list of dictionaries to Dictionary Value list
- Python | Convert List of Dictionary to Tuple list
- Python | Convert 1D list to 2D list of variable length
- Python | Convert list of strings to list of tuples
- Python - Convert Value list elements to List records
- Python | Convert a nested list into a flat list
- Python | Convert List of lists to list of Strings
- Python - Convert Key-Value list Dictionary to List of Lists
- Python | Convert a string representation of list into list
- Python | Convert Integral list to tuple list
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.
Improved By : ManasChhabra2

