![]() |
|
[Tut] Python Convert Set to List [Interactive Guide] - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] Python Convert Set to List [Interactive Guide] (/thread-95394.html) |
[Tut] Python Convert Set to List [Interactive Guide] - xSicKxBot - 06-03-2020 Python Convert Set to List [Interactive Guide] Do you want to convert a Python set to a list? Use the Code: list(...)Code: friendsCode: list(friends)Here’s an example code snippet that converts the set to a list using the Code: list(...)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]
Each list element becomes a new key to the dictionary. For example, the list Code: [1, 2, 3]Code: {1:None, 2:None, 3:None}![]() 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}Code: [0, 3, 8, 9]Solution: Use the Code: sorted(...)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: *Code: sCode: [*s]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: l4https://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.html#code=def%20set_to_list%28s%29%3A%0A%20%20%20%20l%20%3D%20%5B%5D%0A%0A%20%20%20%20%23%20Repeat%20n%20times%20--%3E%20O%28n%29%0A%20%20%20%20for%20x%20in%20s%3A%0A%0A%20%20%20%20%20%20%20%20%23%20Append%20element%20to%20list%20--%3E%20O%281%29%0A%20%20%20%20%20%20%20%20l.append%28x%29%0A%20%20%20%20%20%20%20%20%0A%20%20%20%20return%20s%0A%0Afriends%20%3D%20%7B'Alice',%20'Bob',%20'Ann',%20'Liz',%20'Alice'%7D%0Al%20%3D%20set_to_list%28friends%29%0Aprint%28l%29%0A%23%20%7B'Alice',%20'Liz',%20'Ann',%20'Bob'%7D%0A&codeDivHeight=400&codeDivWidth=350&cumulative=false&curInstr=0&heapPrimitives=nevernest&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false Python Add Set to List Problem: Given a list Code: lCode: sCode: sCode: lExample: Given is list Code: ['Alice', 'Bob', 'Ann']Code: {42, 21}Code: ['Alice', 'Bob', 'Ann', 42, 21]Solution: Use the Code: list.extend(iterable)Code: iterableCode: listCode: 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 callableThe reason is—in all likelihood—that you overwrote the name Code: setCode: setHere’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()Code: s0 = {1, 2}
lst = [1, 2, 3]
s = set(lst)Now, no such error is thrown because the Code: setWhere 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! |