AppDividend
Latest Code Tutorials

How to Convert Python Set to List

Converting one data type to another is a common operation since Python has many working types. Python list is one of the most used data structures because of its performance and simplicity. It is like an array in other programming languages. In this example, we will see how to convert Python set to list using different approaches.

Python set to list

To convert Python set to list:

  1. Use list() method.
  2. Using sorted() function.
  3. Using [*set, ].

Using list() method

To convert Python set to list data type, use the list() method. Likewise, typecasting to a list can be done simply using the list(set) method.

data_set = {"Chilling", "Adventures", "Of", "Sabrina"}

listed_data = list(data_set)
print(listed_data)

Output

['Chilling', 'Of', 'Adventures', 'Sabrina']

You can see that the list() function returns the list, and items are intact. Therefore, by converting the set to a list, the set elements won’t change and will stay as it is.

Use sorted() method

Python sorted() is a built-in function that sorts any sequence. The sorted() method converts the set into a list in a defined order.

def set_to_list(set):
  return sorted(set)

data_set = {"Chilling", "Adventures", "Of", "Sabrina"}
print(data_set)
print(type(data_set))
listed_data = set_to_list(data_set)
print(listed_data)
print(type(listed_data))

Output

{'Adventures', 'Chilling', 'Sabrina', 'Of'}
<class 'set'>
['Adventures', 'Chilling', 'Of', 'Sabrina']
<class 'list'>

In this example, we have defined a set_to_list() function and then defined a set and printed its type using the type() function.

Then called the set_to_list() function that returns the list.

Using [*set, ]

The [*set, ] unwraps the set inside a list literal, created due to the single comma’s presence (, ). The advantage of this approach is that it is fast, but the disadvantage is that it is not readable and not user-friendly.

def set_to_list(set):
  return [*set, ]

data_set = {"Chilling", "Adventures", "Of", "Sabrina"}
print(data_set)
print(type(data_set))
listed_data = set_to_list(data_set)
print(listed_data)
print(type(listed_data))

Output

{'Chilling', 'Adventures', 'Of', 'Sabrina'}
<class 'set'>
['Chilling', 'Adventures', 'Of', 'Sabrina']
<class 'list'>

This example is the same as above with the difference is that the function set_to_list() returns [*set, ] instead of sorted() function.

See also

Python List to String

Python List to DataFrame

Python List to JSON

Python List to Dictionary

Python Set Comprehension

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.