Python: Convert Set to List [2 Methods]

python programs

Problem: How to convert the given set into a list in the Python programming language?

Maethod 1: Using list() Function

The list() function in Python accepts sequences such as set, tuple, etc, and converts them into a list object.

>>> s = set({1, 2, 3, 4, 5})
>>> print('set: ', x)
set:  {1, 2, 3, 4, 5}
>>> l = list(s)
>>> print("list: ",l)
list:  [1, 2, 3, 4, 5]

This is the fastest way to convert any set into a list data structure in Python.

Method 2: Using * (unpacking) operator

The unpacking operator (*) in Python unpacks the values of iterables such as set, tuple, list, etc.

We can reassign all those unpacked values to create a new list object as follows:

>>> s = {1, 2, 3}
>>> l = [*s, ]
>>> print(l)
[1, 2, 3]

Leave a Reply

Your email address will not be published. Required fields are marked *