{"id":114032,"date":"2020-06-11T08:07:39","date_gmt":"2020-06-11T08:07:39","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=9506"},"modified":"2020-06-11T08:07:39","modified_gmt":"2020-06-11T08:07:39","slug":"how-to-merge-lists-into-a-list-of-tuples-6-pythonic-ways","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2020\/06\/11\/how-to-merge-lists-into-a-list-of-tuples-6-pythonic-ways\/","title":{"rendered":"How to Merge Lists into a List of Tuples? [6 Pythonic Ways]"},"content":{"rendered":"<figure class=\"wp-block-image size-large is-resized\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/06\/merge-1024x576.jpg\" alt=\"Merge Lists to List of Tuples\" class=\"wp-image-9536\" width=\"768\" height=\"432\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/06\/merge-scaled.jpg 1024w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/06\/merge-300x169.jpg 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/06\/merge-768x432.jpg 768w\" sizes=\"auto, (max-width: 768px) 100vw, 768px\" \/><\/figure>\n<p class=\"has-background has-luminous-vivid-amber-background-color\"><strong>The most Pythonic way to merge multiple lists <code>l0, l1, ..., ln<\/code> into a list of tuples (grouping together the <code>i<\/code>-th elements) is to use the <code>zip()<\/code> function <code>zip(l0, l1, ..., ln)<\/code>. If you store your lists in a list of lists <code>lst<\/code>, write <code>zip(*lst)<\/code> to unpack all inner lists into the zip function.<\/strong><\/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]\nl2 = [4, 5, 6]\nl = list(zip(l1, l2))\nprint(l)\n# [(1, 4), (2, 5), (3, 6)]<\/pre>\n<p>The proficient use of Python&#8217;s built-in data structures is an integral part of your Python education. This tutorial shows you how you can merge multiple lists into the &#8220;column&#8221; representation&#8212;a list of tuples. By studying these six different ways, you&#8217;ll not only understand how to solve this particular problem, you&#8217;ll also become a better coder overall.<\/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=\"How to Merge Lists into a List of Tuples? [6 Pythonic Ways]\" width=\"1400\" height=\"788\" src=\"https:\/\/www.youtube.com\/embed\/Clk7yPfxia8?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<\/code>, <code>l2<\/code>, &#8230;, <code>ln<\/code>. How to merge them into a list of tuples (column-wise)?<\/p>\n<p><strong>Example<\/strong>: Say, you want to merge the following lists<\/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=\"\">l0 = [0, 'Alice', 4500.00]\nl1 = [1, 'Bob', 6666.66]\nl2 = [2, 'Liz', 9999.99]<\/pre>\n<p>into a list of tuples<\/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=\"\">[(0, 1, 2), ('Alice', 'Bob', 'Liz'), (4500.0, 6666.66, 9999.99)]<\/pre>\n<p>This tutorial shows you different ways to merge multiple lists into a list of tuples in <a href=\"https:\/\/blog.finxter.com\/how-to-check-your-python-version\/\" target=\"_blank\" rel=\"noreferrer noopener\">Python 3<\/a>. You can get a quick overview in our interactive Python shell:<\/p>\n<p> <iframe loading=\"lazy\" src=\"https:\/\/trinket.io\/embed\/python\/3d2e6b11e2\" width=\"100%\" height=\"356\" frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" allowfullscreen><\/iframe> <\/p>\n<p><em><strong>Exercise<\/strong>: Which method needs the least number of characters?<\/em><\/p>\n<h2>Method 1: Zip Function<\/h2>\n<p>The most Pythonic way that merges multiple lists into a list of tuples is the zip function. It accomplishes this in a single line of code&#8212;while being readable, concise, and efficient.<\/p>\n<p>The <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/zip-unzip-python\/\" target=\"_blank\"><code>zip()<\/code> function<\/a> takes one or more iterables and aggregates them to a single one by combining the i-th values of each iterable into a tuple. For example, zip together lists <code>[1, 2, 3]<\/code> and <code>[4, 5, 6]<\/code> to <code>[(1,4), (2,5), (3,6)]<\/code>.<\/p>\n<p>Here&#8217;s the code solution:<\/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=\"\">l0 = [0, 'Alice', 4500.00]\nl1 = [1, 'Bob', 6666.66]\nl2 = [2, 'Liz', 9999.99] print(list(zip(l0, l1, l2)))<\/pre>\n<p>The output is the following list of tuples:<\/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=\"\">[(0, 1, 2), ('Alice', 'Bob', 'Liz'), (4500.0, 6666.66, 9999.99)]<\/pre>\n<p>Note that the return value of the <code>zip()<\/code> function is a <code>zip<\/code> object. You need to convert it to a list using the <code>list(...)<\/code> constructor to create a <a href=\"https:\/\/blog.finxter.com\/how-to-convert-list-of-tuples-to-list-of-lists-in-python\/\" target=\"_blank\" rel=\"noreferrer noopener\">list of tuples<\/a>.<\/p>\n<p>If you have stored the input lists in a single <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-list-of-lists\/\" target=\"_blank\">list of lists<\/a>, the following method is best for you!<\/p>\n<h2>Method 2: Zip Function with Unpacking<\/h2>\n<p>You can use the <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/what-is-asterisk-in-python\/\" target=\"_blank\">asterisk operator<\/a> <code>*lst<\/code> to unpack all inner elements from a given list <code>lst<\/code>. Especially if you want to merge many different lists, this can significantly reduce the length of your code. Instead of writing <code>zip(lst[0], lst[1], ..., lst[n])<\/code>, simplify to <code>zip(*lst)<\/code> to unpack all inner lists into the zip function and accomplish the same thing!<\/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 = [[0, 'Alice', 4500.00], [1, 'Bob', 6666.66], [2, 'Liz', 9999.99]]\nprint(list(zip(*lst)))\n<\/pre>\n<p>This generates the list of tuples:<\/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=\"\">[(0, 1, 2), ('Alice', 'Bob', 'Liz'), (4500.0, 6666.66, 9999.99)]<\/pre>\n<p>I&#8217;d consider using the <code>zip()<\/code> function with unpacking the most Pythonic way to merge multiple lists into a list of tuples.<\/p>\n<h2>Method 3: List Comprehension<\/h2>\n<p>List comprehension is a compact way of creating lists. The simple formula is <code>[expression + context]<\/code>.<\/p>\n<ul>\n<li><strong>Expression<\/strong>: What to do with each list element?<\/li>\n<li><strong>Context<\/strong>: What elements to select? The context consists of an arbitrary number of <code>for<\/code> and <code>if<\/code> statements.<\/li>\n<\/ul>\n<p>The example <code>[x for x in range(3)]<\/code> creates the list <code>[0, 1, 2]<\/code>. <\/p>\n<p><strong>Related Article<\/strong>: <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/list-comprehension\/\" target=\"_blank\">You can read more about list comprehension in my ultimate guide on this blog.<\/a><\/p>\n<p>You can use a straightforward list comprehension statement <code>[(l0[i], l1[i], l2[i]) for i in range(len(l0))]<\/code> to merge multiple lists into a list of tuples:<\/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=\"\">l0 = [0, 'Alice', 4500.00]\nl1 = [1, 'Bob', 6666.66]\nl2 = [2, 'Liz', 9999.99] print([(l0[i], l1[i], l2[i]) for i in range(len(l0))])<\/pre>\n<p>The output produces the merged list of tuples:<\/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=\"\">[(0, 1, 2), ('Alice', 'Bob', 'Liz'), (4500.0, 6666.66, 9999.99)]<\/pre>\n<p>This method is short and efficient. It may not be too readable for you if you&#8217;re a beginner coder&#8212;but advanced coders usually have no problems understanding this one-liner. If you love to learn everything there is about one-liner Python code snippets, check out my new book &#8220;<a href=\"https:\/\/www.amazon.com\/gp\/product\/B07ZY7XMX8\" target=\"_blank\" rel=\"noreferrer noopener\">Python One-Liners<\/a>&#8221; (published with San Francisco Publisher NoStarch in 2020).<\/p>\n<h2>Method 4: Simple Loop<\/h2>\n<p>Sure, you can skip all the fancy Python and just use a simple loop as well! Here&#8217;s how this works:<\/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=\"\">l0 = [0, 'Alice', 4500.00]\nl1 = [1, 'Bob', 6666.66]\nl2 = [2, 'Liz', 9999.99] lst = []\nfor i in range(len(l0)): lst.append((l0[i], l1[i], l2[i]))\nprint(lst)<\/pre>\n<p>The output is the merged list of tuples:<\/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=\"\">[(0, 1, 2), ('Alice', 'Bob', 'Liz'), (4500.0, 6666.66, 9999.99)]<\/pre>\n<p>Especially coders who come to Python from another programming language such as <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-vs-go-which-language-you-should-choose\/\" target=\"_blank\">Go<\/a>, <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/what-are-pythons-disadvantages\/\" target=\"_blank\">C++<\/a>, or Java like this approach. They&#8217;re used to <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-loops\/\" target=\"_blank\">writing loops<\/a> and they can quickly grasp what&#8217;s going on in this code snippet. <\/p>\n<p>You can visualize the execution of this code snippet in the interactive widget:<\/p>\n<p> <iframe loading=\"lazy\" width=\"800\" height=\"500\" frameborder=\"0\" src=\"https:\/\/pythontutor.com\/iframe-embed.html#code=l0%20%3D%20%5B0,%20'Alice',%204500.00%5D%0Al1%20%3D%20%5B1,%20'Bob',%206666.66%5D%0Al2%20%3D%20%5B2,%20'Liz',%209999.99%5D%0A%0Alst%20%3D%20%5B%5D%0Afor%20i%20in%20range%28len%28l0%29%29%3A%0A%20%20%20%20lst.append%28%28l0%5Bi%5D,%20l1%5Bi%5D,%20l2%5Bi%5D%29%29%0Aprint%28lst%29&#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<p><em><strong>Exercise<\/strong>: Click &#8220;Next&#8221; to see how the memory usage unfolds when running the code.<\/em><\/p>\n<h2>Method 5: Enumerate<\/h2>\n<p>The <code><a href=\"https:\/\/blog.finxter.com\/the-top-18-best-python-tricks\/\">enumerate()<\/a><\/code> method is considered to be <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/whats-the-best-pep8-python-style-checker\/\" target=\"_blank\">better Python style<\/a> in many scenarios&#8212;for example, if you want to iterate over all indices of a list. In my opinion, it&#8217;s slightly better than using <code>range(len(l))<\/code>. Here&#8217;s how you can use <code>enumerate()<\/code> in your code to merge multiple lists into a single list of tuples:<\/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=\"\">l0 = [0, 'Alice', 4500.00]\nl1 = [1, 'Bob', 6666.66]\nl2 = [2, 'Liz', 9999.99] lst = []\nfor i,x in enumerate(l0): lst.append((x,l1[i],l2[i]))\nprint(lst)<\/pre>\n<p>The output is the list of tuples:<\/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=\"\">[(0, 1, 2), ('Alice', 'Bob', 'Liz'), (4500.0, 6666.66, 9999.99)]<\/pre>\n<p>Still not satisfied? Let&#8217;s have a look at <a href=\"https:\/\/blog.finxter.com\/about-guidos-fate-of-reduce-in-python-3000\/\" target=\"_blank\" rel=\"noreferrer noopener\">functional programming<\/a>.<\/p>\n<h2>Method 6: Map + Lambda<\/h2>\n<p>With Python\u2019s <code><a href=\"https:\/\/blog.finxter.com\/which-is-faster-list-comprehension-or-map-function-in-python\/\">map()<\/a><\/code> function, you can apply a specific function to each element of an iterable. It takes two arguments:<\/p>\n<ul>\n<li><strong>Function<\/strong>: In most cases, this is a <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/a-simple-introduction-of-the-lambda-function-in-python\/\" target=\"_blank\">lambda function <\/a>you define on the fly. This is the function which you are going to apply to each element of an\u2026<\/li>\n<li><strong>Iterable<\/strong>: This is an iterable that you convert into a new iterable where each element is the result of the applied <code>map()<\/code> function.<\/li>\n<\/ul>\n<p>The result is a <a href=\"https:\/\/blog.finxter.com\/daily-python-puzzle-string-encrpytion-ord-function-map-function\/\" target=\"_blank\" rel=\"noreferrer noopener\"><code>map<\/code> object<\/a>. What many coders don&#8217;t know is that the <code>map()<\/code> function also allows multiple iterables. In this case, the lambda function takes multiple arguments&#8212;one for each iterable. It then creates an iterable of tuples and returns this as a result.<\/p>\n<p>Here&#8217;s how you can create a list of tuples from a few given lists:<\/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=\"\">l0 = [0, 'Alice', 4500.00]\nl1 = [1, 'Bob', 6666.66]\nl2 = [2, 'Liz', 9999.99] lst = list(map(lambda x, y, z: (x, y, z), l0, l1, l2))\nprint(lst)<\/pre>\n<p>The output is the merged list of tuples:<\/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=\"\">[(0, 1, 2), ('Alice', 'Bob', 'Liz'), (4500.0, 6666.66, 9999.99)]<\/pre>\n<p>This is both an efficient and readable way to merge multiple lists into a list of tuples. The fact that it isn&#8217;t well-known to use the <code><a href=\"https:\/\/blog.finxter.com\/about-guidos-fate-of-reduce-in-python-3000\/\">map()<\/a><\/code> function with multiple arguments doesn&#8217;t make this less beautiful. <\/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>The most Pythonic way to merge multiple lists l0, l1, &#8230;, ln into a list of tuples (grouping together the i-th elements) is to use the zip() function zip(l0, l1, &#8230;, ln). If you store your lists in a list of lists lst, write zip(*lst) to unpack all inner lists into the zip function. l1 [&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-114032","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\/114032","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=114032"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/114032\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=114032"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=114032"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=114032"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}