{"id":115112,"date":"2020-07-07T09:34:19","date_gmt":"2020-07-07T09:34:19","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=10555"},"modified":"2020-07-07T09:34:19","modified_gmt":"2020-07-07T09:34:19","slug":"zip-with-list-output-instead-of-tuple-most-pythonic-way","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2020\/07\/07\/zip-with-list-output-instead-of-tuple-most-pythonic-way\/","title":{"rendered":"Zip With List Output Instead of Tuple | Most Pythonic Way"},"content":{"rendered":"<p class=\"has-luminous-vivid-amber-background-color has-background\"><strong>Short answer<\/strong>: Per default, the <code>zip()<\/code> function returns a zip object of tuples. To obtain a <em>list of lists<\/em> as an output, use the list comprehension statement <code>[list(x) for x in zip(l1, l2)]<\/code> that converts each tuple to a list and stores the converted lists in a new nested list object.<\/p>\n<p><em>Intermediate Python coders know the <code>zip()<\/code> function. But if you&#8217;re like me, you&#8217;ve often cursed the output of the zip function: first of all, it&#8217;s a zip object (and not a list), and, second, the individual zipped elements are tuples. But what if you need a list of lists as output? This article will show you the most Pythonic way of doing this.<\/em><\/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 zip list of lists instead list of tuples\" width=\"1400\" height=\"788\" src=\"https:\/\/www.youtube.com\/embed\/MM1PBzZjmh0?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen><\/iframe><\/div>\n<\/div>\n<\/figure>\n<p><strong>Problem<\/strong>: Given a number of lists <code>l1, l2, ...<\/code>. How ot <a href=\"https:\/\/blog.finxter.com\/python-ziiiiiiip-a-helpful-guide\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python Ziiiiiiip! [A helpful guide]\">zip <\/a>the i-th elements of those lists together and obtain a list<a href=\"https:\/\/blog.finxter.com\/python-list-of-lists\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python List of Lists \u2013 A Helpful Illustrated Guide to Nested Lists in Python\"> of lists<\/a>?<\/p>\n<p><strong>Example<\/strong>: Given two lists <code>[1, 2, 3, 4]<\/code> and <code>['Alice', 'Bob', 'Ann', 'Liz']<\/code> and you want the list of lists <code>[[1, 'Alice'], [2, 'Bob'], [3, 'Ann'], [4, 'Liz']]<\/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=\"\">l1 = [1, 2, 3, 4]\nl2 = ['Alice', 'Bob', 'Ann', 'Liz']\n# ... calculate result ...\n# Output: [[1, 'Alice'], [2, 'Bob'], [3, 'Ann'], [4, 'Liz']]<\/pre>\n<p>Here&#8217;s a quick overview of our solutions:<\/p>\n<p> <iframe loading=\"lazy\" src=\"https:\/\/trinket.io\/embed\/python\/07d4e000fe\" width=\"100%\" height=\"500\" frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" allowfullscreen><\/iframe> <\/p>\n<p><em><strong>Exercise<\/strong>: Create a new list <code>l3<\/code> and change the four methods to zip together all three <a href=\"https:\/\/blog.finxter.com\/python-lists\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"The Ultimate Guide to Python Lists\">lists <\/a>(instead of only two). <\/em><\/p>\n<h2>Method 1: Generator Expression<\/h2>\n<p>The first method uses a <a href=\"https:\/\/blog.finxter.com\/how-to-use-generator-expressions-in-python-dictionaries\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"How to Use Generator Expressions in Python Dictionaries\">generator expression<\/a> and converts the resulting iterable 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=\"\">\nl1 = [1, 2, 3, 4]\nl2 = ['Alice', 'Bob', 'Ann', 'Liz'] # Method 1\nzipped = list(list(x) for x in zip(l1, l2)) print(zipped)\n# [[1, 'Alice'], [2, 'Bob'], [3, 'Ann'], [4, 'Liz']]<\/pre>\n<p>This is efficient but not the most concise way of accomplishing this task.<\/p>\n<h2>Method 2: List Comprehension<\/h2>\n<p>A better way is to use <a href=\"https:\/\/blog.finxter.com\/list-comprehension\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"List Comprehension in Python \u2014 A Helpful Illustrated Guide\">list comprehension<\/a> which is like a generator expression but it creates a list directly without the need to convert an iterable to a list (as in Method 1). <\/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=\"\">l1 = [1, 2, 3, 4]\nl2 = ['Alice', 'Bob', 'Ann', 'Liz'] # Method 2:\nzipped = [list(x) for x in zip(l1, l2)] print(zipped)\n# [[1, 'Alice'], [2, 'Bob'], [3, 'Ann'], [4, 'Liz']]\n<\/pre>\n<h2>Method 3: For Loop and Zip<\/h2>\n<p>Coders who don&#8217;t like list comprehension and generator expressions (or, who don&#8217;t understand these beautiful Python features) often use a simple <a href=\"https:\/\/blog.finxter.com\/python-loops\/\" title=\"Python Loops\" target=\"_blank\" rel=\"noreferrer noopener\">for loop<\/a>. In the loop body, you convert each tuple in the <a href=\"https:\/\/blog.finxter.com\/zip-unzip-python\/\" title=\"Zip &amp; Unzip: How Does It Work in Python?\" target=\"_blank\" rel=\"noreferrer noopener\">zip <\/a>object to a list and <a href=\"https:\/\/blog.finxter.com\/python-list-append\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python List append() Method\">append <\/a>this list to the nested list <code>zipped<\/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=\"\">l1 = [1, 2, 3, 4]\nl2 = ['Alice', 'Bob', 'Ann', 'Liz'] # Method 3:\nzipped = []\nfor t in zip(l1, l2): zipped.append(list(t)) print(zipped)\n# [[1, 'Alice'], [2, 'Bob'], [3, 'Ann'], [4, 'Liz']]\n<\/pre>\n<p>This method is readable but less concise.<\/p>\n<h2>Method 4: For Loop and Indexing<\/h2>\n<p>This method is often used by coders who know neither the <code>zip()<\/code> method, nor list comprehension, nor generator expressions: loop over all indices and append a new list obtained by grouping the i-th elements to the list. <\/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=\"\">l1 = [1, 2, 3, 4]\nl2 = ['Alice', 'Bob', 'Ann', 'Liz'] # Method 4:\nzipped = []\nfor i in range(len(l1)): zipped.append([l1[i], l2[i]]) print(zipped)\n# [[1, 'Alice'], [2, 'Bob'], [3, 'Ann'], [4, 'Liz']]\n<\/pre>\n<p>However, this method is least Pythonic, lengthy, and it works only for equally-sized lists.<\/p>\n<p><em><strong>Exercise<\/strong>: What happens if the first list has more elements than the second list?<\/em> <\/p>\n<h2>Method 5: Zip() + Map() + List()<\/h2>\n<p>A functional way of solving this problem is the <a href=\"https:\/\/blog.finxter.com\/daily-python-puzzle-string-encrpytion-ord-function-map-function\/\" title=\"Mastering the Python Map Function [+Video]\" target=\"_blank\" rel=\"noreferrer noopener\">map()<\/a> function that applies a function to each element of an iterable and returns a map object. You can pass the <code>list()<\/code> constructor to the <code>map()<\/code> function to convert each tuple in the zip object to a list. You can then convert the map object to a list. <\/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=\"\">l1 = [1, 2, 3, 4]\nl2 = ['Alice', 'Bob', 'Ann', 'Liz'] # Method 5\nprint(list(map(list,zip(l1, l2))))\n# [[1, 'Alice'], [2, 'Bob'], [3, 'Ann'], [4, 'Liz']]<\/pre>\n<p>I don&#8217;t recommend this method because functional programming may be difficult to understand for many beginner coders. Guido van Rossum, the creator of Python, <a href=\"https:\/\/blog.finxter.com\/about-guidos-fate-of-reduce-in-python-3000\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"About Guido\u2019s Article: \u201cFate of Reduce() in Python 3000\u201d\">disliked functional programming<\/a> as well.<\/p>\n<h2>Discussion<\/h2>\n<p>The most Pythonic way to create a list of lists by zipping together multiple lists is the list comprehension statement <code>[list(x) for x in zip(l1, l2)]<\/code>. List comprehension is fast, efficient, concise, and readable. You can also extend it to the general case by adding more lists to the zip function: <code>[list(x) for x in zip(l1, l2, l3, ..., ln)]<\/code>. The <code>zip()<\/code> function is also robust against lists of different lengths. In this case, the elements up to the maximal index of the shortest list are zipped. <\/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>Short answer: Per default, the zip() function returns a zip object of tuples. To obtain a list of lists as an output, use the list comprehension statement [list(x) for x in zip(l1, l2)] that converts each tuple to a list and stores the converted lists in a new nested list object. Intermediate Python coders know [&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-115112","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\/115112","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=115112"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/115112\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=115112"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=115112"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=115112"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}