[Tut] Python Convert Set to List [Interactive Guide] - Printable Version +- Sick Gaming (https://www.sickgaming.net) +-- Forum: Programming (https://www.sickgaming.net/forum-76.html) +--- Forum: Python (https://www.sickgaming.net/forum-83.html) +--- Thread: [Tut] Python Convert Set to List [Interactive Guide] (/thread-95240.html) |
[Tut] Python Convert Set to List [Interactive Guide] - xSicKxBot - 05-26-2020 Python Convert Set to List [Interactive Guide] <div><p><strong>Do you want to convert a Python set to a list? Use the <code>list(...)</code> constructor and pass the set object as an argument. For example, to convert a set of strings <code>friends</code> into a list, use the code expression <code>list(friends)</code>.</strong></p> <figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"> <div class="wp-block-embed__wrapper"> <div class="ast-oembed-container"><iframe title="Python Convert Set to List [Interactive Guide]" width="1400" height="788" src="https://www.youtube.com/embed/7oRU7UD6OF4?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div> </div> </figure> <p>Here’s an example code snippet that converts the set to a list using the <code>list(...)</code> constructor:</p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># 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'] '''</pre> <p>Try it in our interactive Python shell:</p> <p> <iframe src="https://trinket.io/embed/python/41da5ec97a" width="100%" height="356" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> </p> <p><em><strong>Exercise</strong>: Add more elements to the set. Does the list always have the same order as the set?</em></p> <h2>Python Set to List Order</h2> <p>A set is defined as an <a rel="noreferrer noopener" href="https://blog.finxter.com/sets-in-python/" target="_blank"><em>unordered collection of unique elements</em></a>. 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.</p> <h2>Python Set to List Keep Order</h2> <p>But what if you want to preserve the order when converting a set to a list (and, maybe, back)?</p> <p><a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-remove-duplicates-from-a-python-list/" target="_blank">I’ve written a detailed article on this topic so check it out if you need more info.</a></p> <p>Create a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-dictionary/" target="_blank">dictionary </a>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.</p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">lst = ['Alice', 'Bob', 'Bob', 1, 1, 1, 2, 3, 3] print(list(dict.fromkeys(lst))) # ['Alice', 'Bob', 1, 2, 3]</pre> <ol> <li>Convert the list to a dictionary with <code>dict.fromkeys(lst)</code>. </li> <li>Convert the dictionary into a list with <code>list(dict)</code>.</li> </ol> <p>Each list element becomes a new <a href="https://blog.finxter.com/how-to-get-the-key-with-minimum-value-in-a-python-dictionary/" target="_blank" rel="noreferrer noopener">key to the dictionary</a>. For example, the list <code>[1, 2, 3]</code> becomes the dictionary <code>{1:None, 2:None, 3:None}</code>. 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.</p> <figure class="wp-block-image size-large is-resized"><img src="https://blog.finxter.com/wp-content/uploads/2020/04/removeDupsPython-1024x576.jpg" alt="" class="wp-image-7701" width="512" height="288" srcset="https://blog.finxter.com/wp-content/uploads/2020/04/removeDupsPython-scaled.jpg 1024w, https://blog.finxter.com/wp-content/uploads/2020/04/removeDupsPython-300x169.jpg 300w, https://blog.finxter.com/wp-content/uploads/2020/04/removeDupsPython-768x432.jpg 768w" sizes="(max-width: 512px) 100vw, 512px" /></figure> <p>As dictionary values, you take dummy values (per default).</p> <p>Then, you convert the dictionary back to a list, throwing away the dummy values. </p> <p>Here’s the code:</p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> 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]</pre> <p>This way, you can simply use the ordered dictionary data type. </p> <p><strong>Related blog articles:</strong></p> <ul> <li><a href="https://blog.finxter.com/python-list-to-set/" target="_blank" rel="noreferrer noopener">Python List to Set Conversion</a></li> <li><a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-remove-duplicates-from-a-python-list-of-lists/" target="_blank">Python Remove Duplicates From List of Lists</a></li> <li><a rel="noreferrer noopener" href="https://blog.finxter.com/python-list-remove/" target="_blank">Python List Remove</a></li> <li><a rel="noreferrer noopener" href="https://blog.finxter.com/python-dictionary/" target="_blank">The Ultimate Guide to Python Dictionaries!</a></li> </ul> <h2>Python Set to List Sorted</h2> <p><strong>Problem</strong>: Convert a set to a <a href="https://blog.finxter.com/python-list-sort/" target="_blank" rel="noreferrer noopener">sorted list</a>.</p> <p><strong>Example</strong>: Convert set <code>{0, 9, 8, 3}</code> to the sorted list <code>[0, 3, 8, 9]</code>. </p> <p><strong>Solution</strong>: Use the <code>sorted(...)</code> method that creates a new <a href="https://blog.finxter.com/python-lists/" target="_blank" rel="noreferrer noopener">list </a>from any iterable you pass as an argument.</p> <p><strong>Code</strong>: Let’s have a look at the source code that solves the problem!</p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">s = {0, 9, 8, 3} l = sorted(s) print(l) # [0, 3, 8, 9]</pre> <p><em><strong>Exercise</strong>: Can you modify the code so that the elements are sorted in descending order?</em></p> <p> <iframe src="https://trinket.io/embed/python/852f9ef232" width="100%" height="356" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> </p> <h2>Python Set to List Unpacking</h2> <p>An alternative method to convert a set to a list is <a rel="noreferrer noopener" href="https://blog.finxter.com/what-is-asterisk-in-python/" target="_blank">unpacking </a>with the asterisk operator <code>*</code>. You can simply unpack all elements in set <code>s</code> into an empty list by using the asterisk as a prefix within an empty list like this <code>[*s]</code>. 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]</code>. </p> <p>Here’s the minimal example:</p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">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] '''</pre> <p><em><strong>Exercise</strong>: Play with the following code unpacking a fourth set into a new list <code>l4</code>. </em></p> <p> <iframe src="https://trinket.io/embed/python/c63838618a" width="100%" height="356" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> </p> <h2>Python Set to List Complexity</h2> <p>The <a rel="noreferrer noopener" href="https://blog.finxter.com/runtime-complexity-of-python-list-methods-easy-table-lookup/" target="_blank">time complexity</a> of converting a <a rel="noreferrer noopener" href="https://blog.finxter.com/sets-in-python/" target="_blank">set</a> to a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" target="_blank">list</a> is linear in the number of list elements. So, if the set has <em>n</em> elements, the asymptotic complexity is <em>O(n)</em>. The reason is that you need to<a rel="noreferrer noopener" href="https://blog.finxter.com/python-loops/" target="_blank"> iterate over each element</a> in the set which is <em>O(n)</em>, and append this element to the list which is <em>O(1)</em>. Together the complexity is <em>O(n) * O(1) = O(n * 1) = O(n)</em>. </p> <p>Here’s the pseudo-code implementation of the<em> set to list </em>conversion method:</p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">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'} </pre> <p>Need help understanding this code snippet? Try visualizing it in your browser—just click “Next” to see what the code does in memory:</p> <p> <iframe width="800" height="500" frameborder="0" src="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"> </iframe> </p> <h2>Python Add Set to List</h2> <p><strong>Problem</strong>: Given a list <code>l</code> and a set <code>s</code>. Add all elements in <code>s</code> to list <code>l</code>. </p> <p><strong>Example</strong>: Given is list <code>['Alice', 'Bob', 'Ann']</code> and set <code>{42, 21}</code>. You want to get the resulting list <code>['Alice', 'Bob', 'Ann', 42, 21]</code>.</p> <p><strong>Solution</strong>: Use the <code>list.extend(iterable)</code> method to add all elements in the <code>iterable</code> to the <code>list</code>.</p> <p><strong>Code</strong>: The following code accomplishes this.</p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">l = ['Alice', 'Bob', 'Ann'] s = {42, 21} l.extend(s) print(l) # ['Alice', 'Bob', 'Ann', 42, 21]</pre> <p><em><strong>Exercise</strong>: <a rel="noreferrer noopener" href="https://blog.finxter.com/subscribe/" target="_blank">download your free Python cheat sheets and join my free community of Python coders who love their trade.</a></em></p> <h2>TypeError: ‘set’ object is not callable</h2> <p>Sometimes you can see the following seemingly strange behavior (e.g., <a rel="noreferrer noopener" href="https://stackoverflow.com/questions/6828722/python-set-to-list" target="_blank">here</a>):</p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">s = set([1, 2, 3]) l = list(s)</pre> <p>The output may give you the following cryptic error message:</p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">TypeError: 'set' object is not callable</pre> <p>The reason is—in all likelihood—that you overwrote the name <code>set</code> in your namespace. This happens if you assign a value to a variable called <em>‘set’</em>. Python will assume that <code>set</code> is a variable—and tells you that you cannot call variables.</p> <p>Here’s code that will cause this issue:</p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">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 '''</pre> <p>You can fix it by using another variable name so that the built-in function <code>set()</code> is not overshadowed:</p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">s0 = {1, 2} lst = [1, 2, 3] s = set(lst)</pre> <p>Now, no such error is thrown because the <code>set</code> name correctly points to the Python built-in constructor function.</p> <h2>Where to Go From Here?</h2> <p>Enough theory, let’s get some practice!</p> <p>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?</p> <p><strong>Practice projects is how you sharpen your saw in coding!</strong></p> <p>Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?</p> <p>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.</p> <p>Join my free webinar <a rel="noreferrer noopener" href="https://blog.finxter.com/webinar-freelancer/" target="_blank">“How to Build Your High-Income Skill Python”</a> and watch how I grew my coding business online and how you can, too—from the comfort of your own home.</p> <p><a href="https://blog.finxter.com/webinar-freelancer/" target="_blank" rel="noreferrer noopener">Join the free webinar now!</a></p> </div> https://www.sickgaming.net/blog/2020/05/25/python-convert-set-to-list-interactive-guide/ |