Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Convert set into a list in Python
Converting a set into a list is a common task in Python data analysis. Since sets are unordered collections and lists are ordered, this conversion allows you to access elements by index and maintain a specific order.
Using list() Function
The most straightforward approach is using the built−in list() function, which directly converts a set into a list ?
setA = {'Mon', 'day', '7pm'}
# Given Set
print("Given set:", setA)
# Convert set to list
result = list(setA)
# Result
print("Final list:", result)
Given set: {'7pm', 'day', 'Mon'}
Final list: ['7pm', 'day', 'Mon']
Using Unpacking Operator (*)
The unpacking operator * can extract elements from a set and place them inside square brackets to create a list ?
setA = {'Mon', 'day', '7pm'}
# Given Set
print("Given set:", setA)
# Convert using unpacking operator
result = [*setA]
# Result
print("Final list:", result)
Given set: {'Mon', '7pm', 'day'}
Final list: ['Mon', '7pm', 'day']
Using List Comprehension
List comprehension provides another way to convert a set to a list, useful when you need to apply transformations during conversion ?
setA = {'Mon', 'day', '7pm'}
# Given Set
print("Given set:", setA)
# Convert using list comprehension
result = [item for item in setA]
# Result
print("Final list:", result)
Given set: {'Mon', '7pm', 'day'}
Final list: ['Mon', '7pm', 'day']
Comparison
| Method | Syntax | Best For |
|---|---|---|
list() |
list(set_name) |
Simple conversion |
Unpacking *
|
[*set_name] |
Concise syntax |
| List comprehension | [item for item in set_name] |
When applying transformations |
Key Points
- Sets are unordered, so the resulting list order may vary between runs
- All methods preserve the original set unchanged
- The
list()function is the most readable and commonly used approach
Conclusion
Use list() for straightforward set−to−list conversion. The unpacking operator * offers concise syntax, while list comprehension is ideal when you need to transform elements during conversion.
