We can convert a Set to List in Python using the built-in list[] method. Lets take a look at some examples using this function.
Methods to Convert a Set to List in Python
Well go over simple methods that will allow the conversion of a python set object to a list object quickly.
1. Using list[] Function
The list[] function takes an iterable as an argument and converts that into a List type object. This is a built-in method ready for you to use.
Since a set is also iterable, we can pass it into the list[] method and get our corresponding list.
The output, as expected, will be a list containing the above values.
Note that the order of the list can be random, and not necessarily sorted.
For example, take the below snippet.
Output in my case:
2. Using Manual Iteration
We can also manually add the elements to the list since the set is iterable. This method does not have any real-world advantage over using the list[] method apart from being written by you.
Again, the output is a list:
Convert a frozenset to a list
The Python frozenset object is similar to a set but is immutable. Therefore, we cannot modify the elements of a frozenset. We can convert this type of set too, using list[].
Output
References
- JournalDev article on converting a Set into a List