AppDividend
Latest Code Tutorials

How to Convert Python Set to List

0

Converting one data type to another is a common operation since Python has so many working types. Python list is one of the most used data structure 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, use one of the following approaches.

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

Use list() method

To convert Python set to list data type, use the list() method. Typecasting to list can be done by 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. By converting the set to list, the set elements won’t change, and it will stay as it is.

Use sorted() method

Python sorted() is an inbuilt Function that sorts any sequence.

Use the sorted() method to convert 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.