{"id":113375,"date":"2020-05-25T09:52:14","date_gmt":"2020-05-25T09:52:14","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=8856"},"modified":"2020-05-25T09:52:14","modified_gmt":"2020-05-25T09:52:14","slug":"python-convert-set-to-list-interactive-guide","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2020\/05\/25\/python-convert-set-to-list-interactive-guide\/","title":{"rendered":"Python Convert Set to List [Interactive Guide]"},"content":{"rendered":"<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>\n<figure class=\"wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio\">\n<div class=\"wp-block-embed__wrapper\">\n<div class=\"ast-oembed-container\"><iframe loading=\"lazy\" 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>\n<\/div>\n<\/figure>\n<p>Here&#8217;s an example code snippet that converts the set to a list using the <code>list(...)<\/code> constructor:<\/p>\n<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\nfriends = {'Alice', 'Ann', 'Bob'} # Convert the set to a list\nl = list(friends) # Print both\nprint(friends)\nprint(l) '''\n{'Ann', 'Alice', 'Bob'}\n['Alice', 'Ann', 'Bob'] '''<\/pre>\n<p>Try it in our interactive Python shell:<\/p>\n<p> <iframe loading=\"lazy\" src=\"https:\/\/trinket.io\/embed\/python\/41da5ec97a\" width=\"100%\" height=\"356\" frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" allowfullscreen><\/iframe> <\/p>\n<p><em><strong>Exercise<\/strong>: Add more elements to the set. Does the list always have the same order as the set?<\/em><\/p>\n<h2>Python Set to List Order<\/h2>\n<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 &#8220;unordered&#8221; 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>\n<h2>Python Set to List Keep Order<\/h2>\n<p>But what if you want to preserve the order when converting a set to a list (and, maybe, back)?<\/p>\n<p><a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/how-to-remove-duplicates-from-a-python-list\/\" target=\"_blank\">I&#8217;ve written a detailed article on this topic so check it out if you need more info.<\/a><\/p>\n<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>\n<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]\nprint(list(dict.fromkeys(lst)))\n# ['Alice', 'Bob', 1, 2, 3]<\/pre>\n<ol>\n<li>Convert the list to a dictionary with <code>dict.fromkeys(lst)<\/code>. <\/li>\n<li>Convert the dictionary into a list with <code>list(dict)<\/code>.<\/li>\n<\/ol>\n<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&#8212;there cannot be multiple equal keys.<\/p>\n<figure class=\"wp-block-image size-large is-resized\"><img loading=\"lazy\" decoding=\"async\" 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=\"auto, (max-width: 512px) 100vw, 512px\" \/><\/figure>\n<p>As dictionary values, you take dummy values (per default).<\/p>\n<p>Then, you convert the dictionary back to a list, throwing away the dummy values. <\/p>\n<p>Here&#8217;s the code:<\/p>\n<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]\n>>> dic = dict.fromkeys(lst)\n>>> dic\n{1: None, 3: None, 2: None, 5: None}\n>>> duplicate_free = list(dic)\n>>> duplicate_free\n[1, 3, 2, 5]<\/pre>\n<p>This way, you can simply use the ordered dictionary data type. <\/p>\n<p><strong>Related blog articles:<\/strong><\/p>\n<ul>\n<li><a href=\"https:\/\/blog.finxter.com\/python-list-to-set\/\" target=\"_blank\" rel=\"noreferrer noopener\">Python List to Set Conversion<\/a><\/li>\n<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>\n<li><a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-list-remove\/\" target=\"_blank\">Python List Remove<\/a><\/li>\n<li><a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-dictionary\/\" target=\"_blank\">The Ultimate Guide to Python Dictionaries!<\/a><\/li>\n<\/ul>\n<h2>Python Set to List Sorted<\/h2>\n<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>\n<p><strong>Example<\/strong>: Convert set <code>{0, 9, 8, 3}<\/code> to the sorted list <code>[0, 3, 8, 9]<\/code>. <\/p>\n<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>\n<p><strong>Code<\/strong>: Let&#8217;s have a look at the source code that solves the problem!<\/p>\n<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}\nl = sorted(s)\nprint(l)\n# [0, 3, 8, 9]<\/pre>\n<p><em><strong>Exercise<\/strong>: Can you modify the code so that the elements are sorted in descending order?<\/em><\/p>\n<p> <iframe loading=\"lazy\" src=\"https:\/\/trinket.io\/embed\/python\/852f9ef232\" width=\"100%\" height=\"356\" frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" allowfullscreen><\/iframe> <\/p>\n<h2>Python Set to List Unpacking<\/h2>\n<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&#8217;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>\n<p>Here&#8217;s the minimal example:<\/p>\n<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}\ns2 = {3, 4}\ns3 = {5, 6, 7, 8} l1 = [*s1]\nl2 = [*s1, *s2]\nl3 = [*s1, *s2, *s3] print(l1)\nprint(l2)\nprint(l3) '''\n[1, 2]\n[1, 2, 3, 4]\n[1, 2, 3, 4, 8, 5, 6, 7] '''<\/pre>\n<p><em><strong>Exercise<\/strong>: Play with the following code unpacking a fourth set into a new list <code>l4<\/code>. <\/em><\/p>\n<p> <iframe loading=\"lazy\" src=\"https:\/\/trinket.io\/embed\/python\/c63838618a\" width=\"100%\" height=\"356\" frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" allowfullscreen><\/iframe> <\/p>\n<h2>Python Set to List Complexity<\/h2>\n<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>\n<p>Here&#8217;s the pseudo-code implementation of the<em> set to list <\/em>conversion method:<\/p>\n<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'}\nl = set_to_list(friends)\nprint(l)\n# {'Alice', 'Liz', 'Ann', 'Bob'}\n<\/pre>\n<p>Need help understanding this code snippet? Try visualizing it in your browser&#8212;just click &#8220;Next&#8221; to see what the code does in memory:<\/p>\n<p> <iframe loading=\"lazy\" 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&#038;codeDivHeight=400&#038;codeDivWidth=350&#038;cumulative=false&#038;curInstr=0&#038;heapPrimitives=nevernest&#038;origin=opt-frontend.js&#038;py=3&#038;rawInputLstJSON=%5B%5D&#038;textReferences=false\"> <\/iframe> <\/p>\n<h2>Python Add Set to List<\/h2>\n<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>\n<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>\n<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>\n<p><strong>Code<\/strong>: The following code accomplishes this.<\/p>\n<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']\ns = {42, 21}\nl.extend(s)\nprint(l)\n# ['Alice', 'Bob', 'Ann', 42, 21]<\/pre>\n<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>\n<h2>TypeError: &#8216;set&#8217; object is not callable<\/h2>\n<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>\n<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])\nl = list(s)<\/pre>\n<p>The output may give you the following cryptic error message:<\/p>\n<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>\n<p>The reason is&#8212;in all likelihood&#8212;that you overwrote the name <code>set<\/code> in your namespace. This happens if you assign a value to a variable called <em>&#8216;set&#8217;<\/em>. Python will assume that <code>set<\/code> is a variable&#8212;and tells you that you cannot call variables.<\/p>\n<p>Here&#8217;s code that will cause this issue:<\/p>\n<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}\nlst = [1, 2, 3]\ns = set(lst) '''\nTraceback (most recent call last): File \"C:\\Users\\xcent\\Desktop\\code.py\", line 3, in &lt;module> s = set(lst)\nTypeError: 'set' object is not callable '''<\/pre>\n<p>You can fix it by using another variable name so that the built-in function <code>set()<\/code> is not overshadowed:<\/p>\n<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}\nlst = [1, 2, 3]\ns = set(lst)<\/pre>\n<p>Now, no such error is thrown because the <code>set<\/code> name correctly points to the Python built-in constructor function.<\/p>\n<h2>Where to Go From Here?<\/h2>\n<p>Enough theory, let\u2019s get some practice!<\/p>\n<p>To become successful in coding, you need to get out there and solve real problems for real people. That\u2019s how you can become a six-figure earner easily. And that\u2019s how you polish the skills you really need in practice. After all, what\u2019s the use of learning theory that nobody ever needs?<\/p>\n<p><strong>Practice projects is how you sharpen your saw in coding!<\/strong><\/p>\n<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>\n<p>Then become a Python freelance developer! It\u2019s the best way of approaching the task of improving your Python skills\u2014even if you are a complete beginner.<\/p>\n<p>Join my free webinar <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/webinar-freelancer\/\" target=\"_blank\">\u201cHow to Build Your High-Income Skill Python\u201d<\/a> and watch how I grew my coding business online and how you can, too\u2014from the comfort of your own home.<\/p>\n<p><a href=\"https:\/\/blog.finxter.com\/webinar-freelancer\/\" target=\"_blank\" rel=\"noreferrer noopener\">Join the free webinar now!<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Do you want to convert a Python set to a list? Use the list(&#8230;) 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&#8217;s an example code snippet that converts the set to a list using the list(&#8230;) [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[857],"tags":[73,468,528],"class_list":["post-113375","post","type-post","status-publish","format-standard","hentry","category-python-tut","tag-programming","tag-python","tag-tutorial"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/113375","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=113375"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/113375\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=113375"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=113375"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=113375"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}