Convert a Set to a Python list
This post will discuss how to convert a set to a list in Python and vice versa.
1. Using constructor
The standard way to convert a set into a list is with the list constructor.
|
1 2 3 4 5 6 7 8 |
if __name__ == '__main__': s = {1, 2, 3} l = list(s) print(l) # [1, 2, 3] |
Similarly, you can use the set constructor to convert a list into a set.
|
1 2 3 4 5 6 7 8 |
if __name__ == '__main__': l = [1, 2, 3] s = set(l) print(s) # {1, 2, 3} |
2. Using Iterable Unpacking Operator
Here, the idea is to use the *-operator to unpack the items from the set inside [] syntax, which would convert a set into a list.
|
1 2 3 4 5 6 7 8 |
if __name__ == '__main__': s = {1, 2, 3} l = [*s] print(l) # [1, 2, 3] |
Similarly, to convert a list into a set, you can unpack the list inside the new syntax for set literal {}.
|
1 2 3 4 5 6 7 8 |
if __name__ == '__main__': l = [1, 2, 3] s = {*l} print(s) # {1, 2, 3} |
3. Using extend() function
Another solution to convert a set into a list is using the extend() function to copy elements of the set into an empty list.
|
1 2 3 4 5 6 7 8 9 |
if __name__ == '__main__': s = {1, 2, 3} l = [] l.extend(s) print(l) # [1, 2, 3] |
Note that the extend() function is not available for a set. However, you can use the union() function to effectively convert a list into a set, as shown below:
|
1 2 3 4 5 6 7 8 |
if __name__ == '__main__': l = [1, 2, 3] s = set().union(l) print(s) # {1, 2, 3} |
That’s all about converting a Set to a list in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)