Convert set into a list in Python

PythonServer Side ProgrammingProgramming

As part of data analysis using Python we may be required to to convert the data container from set to list. In this article we'll see e how to solve this requirement.

With list

This is a straightforward approach in which we directly apply the list function on the given set. The elements get converted into elements of a list.

Example

 Live Demo

setA = {'Mon', 'day', '7pm'}
# Given Set
print("Given set : \n", setA)
res = (list(setA) )
# Result
print("Final list: \n",res)

Output

Running the above code gives us the following result −

Given set :
['7pm', 'Mon', 'day']
Final list:
['7pm', 'Mon', 'day']

With *

The star operator can take in the list and by applying the square brackets around it we get a list.

Example

setA = {'Mon', 'day', '7pm'}
# Given Set
print("Given set : \n", setA)
res = [*setA, ]
# Result
print("Final list: \n",res)

Output

Running the above code gives us the following result −

Given set :
{'Mon', '7pm', 'day'}
Final list:
['Mon', '7pm', 'day']
raja
Published on 20-May-2020 14:40:58
Advertisements