Can we convert set object to list object?

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.

my_list = list[my_iterable]

Since a set is also iterable, we can pass it into the list[] method and get our corresponding list.

my_set = set[{1, 4, 3, 5}] my_list = list[my_set] print[my_list]

The output, as expected, will be a list containing the above values.

[1, 3, 4, 5]

Note that the order of the list can be random, and not necessarily sorted.

For example, take the below snippet.

s = set[] s.add["A"] s.add["B"] print[list[s]]

Output in my case:

['B', 'A']

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.

s = set[{1, 2, 3}] a = [] for i in s: a.append[i] print[a]

Again, the output is a list:

[1, 2, 3]

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[].

f_set = frozenset[{1, 3, 2, 5}] a = list[f_set] print[a]

Output

[1, 2, 3, 5]

References

  • JournalDev article on converting a Set into a List

Video liên quan

Chủ Đề