Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python Convert Set to List [Interactive Guide]
1
Python Convert Set to List [Interactive Guide]

Do you want to convert a Python set to a list? Use the
Code:
list(...)
constructor and pass the set object as an argument. For example, to convert a set of strings
Code:
friends
into a list, use the code expression
Code:
list(friends)
.




Here’s an example code snippet that converts the set to a list using the
Code:
list(...)
constructor:

Code:
# 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:

https://trinket.io/embed/python/41da5ec97a

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 dictionaryfrom 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.

Code:
lst = ['Alice', 'Bob', 'Bob', 1, 1, 1, 2, 3, 3] print(list(dict.fromkeys(lst))) # ['Alice', 'Bob', 1, 2, 3]
  1. Convert the list to a dictionary with
    Code:
    dict.fromkeys(lst)
    .

  2. Convert the dictionary into a list with
    Code:
    list(dict)
    .

Each list element becomes a new key to the dictionary. For example, the list
Code:
[1, 2, 3]
becomes the dictionary
Code:
{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.

[Image: removeDupsPython-1024x576.jpg]

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:

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 Set to List Sorted

Problem: Convert a set to a sorted list.

Example: Convert set
Code:
{0, 9, 8, 3}
to the sorted list
Code:
[0, 3, 8, 9]
.

Solution: Use the
Code:
sorted(...)
method that creates a new listfrom any iterable you pass as an argument.

Code: Let’s have a look at the source code that solves the problem!

Code:
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?

https://trinket.io/embed/python/852f9ef232

Python Set to List Unpacking

An alternative method to convert a set to a list is unpackingwith the asterisk operator
Code:
*
. You can simply unpack all elements in set
Code:
s
into an empty list by using the asterisk as a prefix within an empty list like this
Code:
[*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:
Code:
[*s1, *s2, ..., *sn]
.

Here’s the minimal example:

Code:
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
Code:
l4
.


https://trinket.io/embed/python/c63838618a

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 toiterate 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:

Code:
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:

https://pythontutor.com/iframe-embed.htm...nces=false

Python Add Set to List

Problem: Given a list
Code:
l
and a set
Code:
s
. Add all elements in
Code:
s
to list
Code:
l
.

Example: Given is list
Code:
['Alice', 'Bob', 'Ann']
and set
Code:
{42, 21}
. You want to get the resulting list
Code:
['Alice', 'Bob', 'Ann', 42, 21]
.

Solution: Use the
Code:
list.extend(iterable)
method to add all elements in the
Code:
iterable
to the
Code:
list
.

Code: The following code accomplishes this.

Code:
l = ['Alice', 'Bob', 'Ann'] s = {42, 21} l.extend(s) print(l) # ['Alice', 'Bob', 'Ann', 42, 21]

Exercise: download your free Python cheat sheets and join my free community of Python coders who love their trade.

TypeError: ‘set’ object is not callable

Sometimes you can see the following seemingly strange behavior (e.g., here):

Code:
s = set([1, 2, 3]) l = list(s)

The output may give you the following cryptic error message:

Code:
TypeError: 'set' object is not callable

The reason is—in all likelihood—that you overwrote the name
Code:
set
in your namespace. This happens if you assign a value to a variable called ‘set’. Python will assume that
Code:
set
is a variable—and tells you that you cannot call variables.

Here’s code that will cause this issue:

Code:
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
Code:
set()
is not overshadowed:

Code:
s0 = {1, 2} lst = [1, 2, 3] s = set(lst)

Now, no such error is thrown because the
Code:
set
name correctly points to the Python built-in constructor function.

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And 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?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become 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.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!
Reply

Users browsing this thread:
1 Guest(s)


Forum Jump: