Do you want to convert a Python set to a list? Use the list(...)
constructor and pass the set object as an argument. For example, to convert a set of strings friends
into a list, use the code expression list(friends)
.
Here’s an example code snippet that converts the set to a list using the list(...)
constructor:
# Create the set of strings friends = {'Alice', 'Ann', 'Bob'} # Convert the set to a list l = list(friends) # Print both print(friends) print(l) ''' {'Ann', 'Alice', 'Bob'} ['Alice', 'Ann', 'Bob'] '''
Try it in our interactive Python shell:
Exercise: Add more elements to the set. Does the list always have the same order as the set?
Python Set to List Order
A set is defined as an unordered collection of unique elements. The keyword is “unordered” here. Python does not guarantee any particular order of the elements in the resulting list. If you convert a set to a list, the elements can have an arbitrary order.
Python Set to List Keep Order
But what if you want to preserve the order when converting a set to a list (and, maybe, back)?
I’ve written a detailed article on this topic so check it out if you need more info.
Create a dictionary from the elements in the list to remove all duplicates and convert the dictionary back to a list. This preserves the order of the original list elements.
lst = ['Alice', 'Bob', 'Bob', 1, 1, 1, 2, 3, 3] print(list(dict.fromkeys(lst))) # ['Alice', 'Bob', 1, 2, 3]
- Convert the list to a dictionary with
dict.fromkeys(lst)
. - Convert the dictionary into a list with
list(dict)
.
Each list element becomes a new key to the dictionary. For example, the list [1, 2, 3]
becomes the dictionary {1:None, 2:None, 3:None}
. All elements that occur multiple times will be assigned to the same key. Thus, the dictionary contains only unique keys—there cannot be multiple equal keys.
As dictionary values, you take dummy values (per default).
Then, you convert the dictionary back to a list, throwing away the dummy values.
Here’s the code:
>>> lst = [1, 1, 1, 3, 2, 5, 5, 2] >>> dic = dict.fromkeys(lst) >>> dic {1: None, 3: None, 2: None, 5: None} >>> duplicate_free = list(dic) >>> duplicate_free [1, 3, 2, 5]
This way, you can simply use the ordered dictionary data type.
Related blog articles:
- Python List to Set Conversion
- Python Remove Duplicates From List of Lists
- Python List Remove
- The Ultimate Guide to Python Dictionaries!
Python Set to List Sorted
Problem: Convert a set to a sorted list.
Example: Convert set {0, 9, 8, 3}
to the sorted list [0, 3, 8, 9]
.
Solution: Use the sorted(...)
method that creates a new list from any iterable you pass as an argument.
Code: Let’s have a look at the source code that solves the problem!
s = {0, 9, 8, 3} l = sorted(s) print(l) # [0, 3, 8, 9]
Exercise: Can you modify the code so that the elements are sorted in descending order?
Python Set to List Unpacking
An alternative method to convert a set to a list is unpacking with the asterisk operator *
. You can simply unpack all elements in set s
into an empty list by using the asterisk as a prefix within an empty list like this [*s]
. It’s a fast and Pythonic way of converting a set to a list. And it has the advantage that you can also convert multiple sets into a single list like this: [*s1, *s2, ..., *sn]
.
Here’s the minimal example:
s1 = {1, 2} s2 = {3, 4} s3 = {5, 6, 7, 8} l1 = [*s1] l2 = [*s1, *s2] l3 = [*s1, *s2, *s3] print(l1) print(l2) print(l3) ''' [1, 2] [1, 2, 3, 4] [1, 2, 3, 4, 8, 5, 6, 7] '''
Exercise: Play with the following code unpacking a fourth set into a new list l4
.
Python Set to List Complexity
The time complexity of converting a set to a list is linear in the number of list elements. So, if the set has n elements, the asymptotic complexity is O(n). The reason is that you need to iterate over each element in the set which is O(n), and append this element to the list which is O(1). Together the complexity is O(n) * O(1) = O(n * 1) = O(n).
Here’s the pseudo-code implementation of the set to list conversion method:
def set_to_list(s): l = [] # Repeat n times --> O(n) for x in s: # Append element to list --> O(1) l.append(x) return s friends = {'Alice', 'Bob', 'Ann', 'Liz', 'Alice'} l = set_to_list(friends) print(l) # {'Alice', 'Liz', 'Ann', 'Bob'}
Need help understanding this code snippet? Try visualizing it in your browser—just click “Next” to see what the code does in memory:
Python Add Set to List
Problem: Given a list l
and a set s
. Add all elements in s
to list l
.
Example: Given is list ['Alice', 'Bob', 'Ann']
and set {42, 21}
. You want to get the resulting list ['Alice', 'Bob', 'Ann', 42, 21]
.
Solution: Use the list.extend(iterable)
method to add all elements in the iterable
to the list
.
Code: The following code accomplishes this.
l = ['Alice', 'Bob', 'Ann'] s = {42, 21} l.extend(s) print(l) # ['Alice', 'Bob', 'Ann', 42, 21]
TypeError: ‘set’ object is not callable
Sometimes you can see the following seemingly strange behavior (e.g., here):
s = set([1, 2, 3]) l = list(s)
The output may give you the following cryptic error message:
TypeError: 'set' object is not callable
The reason is—in all likelihood—that you overwrote the name set
in your namespace. This happens if you assign a value to a variable called ‘set’. Python will assume that set
is a variable—and tells you that you cannot call variables.
Here’s code that will cause this issue:
set = {1, 2} lst = [1, 2, 3] s = set(lst) ''' Traceback (most recent call last): File "C:\Users\xcent\Desktop\code.py", line 3, in <module> s = set(lst) TypeError: 'set' object is not callable '''
You can fix it by using another variable name so that the built-in function set()
is not overshadowed:
s0 = {1, 2} lst = [1, 2, 3] s = set(lst)
Now, no such error is thrown because the set
name correctly points to the Python built-in constructor function.
Where to Go From Here?
Enough theory. Let’s get some practice!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.