Sometimes we have to create a list from the set object. We can use built-in list() function for this.
Let’s look at some examples to convert set to list in Python.
1 2 3 4 5 6 7 8 9 10 11 |
s = {"A", "B", "C"} l1 = list(s) print(type(l1)) print(l1) s = set() s.add("A") s.add("B") l1 = list(s) print(l1) |
Output:
1 2 3 4 5 6 |
<class 'list'> ['B', 'A', 'C'] ['B', 'A'] <img class="alignnone wp-image-22503 size-full" src="http://all-learning.com/wp-content/uploads/2019/01/Python-Set-To-List.png" alt="Python Set To List" width="1200" height="650" /> |
Python Set To List
Python frozenset to list
The frozenset object is an immutable unordered collection of unique elements. So it’s a set that we can’t modify. We can pass a frozenset object to list() function too.
1 2 3 4 5 |
s = frozenset({"A", "B"}) l1 = list(s) print(l1) |
Output: ['B', 'A']
Python list to set
If you need to convert list to set, you can use set() function.
1 2 3 4 5 6 |
l1 = [1, 2, 3, 2, 1] s1 = set(l1) print(type(s1)) print(s1) |
Output:
1 2 3 4 5 |
<class 'set'> {1, 2, 3} <img class="alignnone wp-image-22504 size-full" src="http://all-learning.com/wp-content/uploads/2019/01/Python-List-To-Set.png" alt="Python List To Set" width="1200" height="628" /> |
Python List To Set
You can checkout complete python script and more Python examples from our GitHub Repository.
Reference: list() Documentation