Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Merge Lists into a List of Tuples? [6 Pythonic Ways]

#1
How to Merge Lists into a List of Tuples? [6 Pythonic Ways]

<div><figure class="wp-block-image size-large is-resized"><img 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/uplo...00x169.jpg 300w, https://blog.finxter.com/wp-content/uplo...68x432.jpg 768w" sizes="(max-width: 768px) 100vw, 768px" /></figure>
<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>
<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]
l2 = [4, 5, 6]
l = list(zip(l1, l2))
print(l)
# [(1, 4), (2, 5), (3, 6)]</pre>
<p>The proficient use of Python’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 “column” representation—a list of tuples. By studying these six different ways, you’ll not only understand how to solve this particular problem, you’ll also become a better coder overall.</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="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>
</div>
</figure>
<p><strong>Problem</strong>: Given a number of lists <code>l1</code>, <code>l2</code>, …, <code>ln</code>. How to merge them into a list of tuples (column-wise)?</p>
<p><strong>Example</strong>: Say, you want to merge the following lists</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="">l0 = [0, 'Alice', 4500.00]
l1 = [1, 'Bob', 6666.66]
l2 = [2, 'Liz', 9999.99]</pre>
<p>into a list of tuples</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="">[(0, 1, 2), ('Alice', 'Bob', 'Liz'), (4500.0, 6666.66, 9999.99)]</pre>
<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>
<p> <iframe src="https://trinket.io/embed/python/3d2e6b11e2" width="100%" height="356" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> </p>
<p><em><strong>Exercise</strong>: Which method needs the least number of characters?</em></p>
<h2>Method 1: Zip Function</h2>
<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—while being readable, concise, and efficient.</p>
<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>
<p>Here’s the code solution:</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="">l0 = [0, 'Alice', 4500.00]
l1 = [1, 'Bob', 6666.66]
l2 = [2, 'Liz', 9999.99] print(list(zip(l0, l1, l2)))</pre>
<p>The output is the following list of tuples:</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="">[(0, 1, 2), ('Alice', 'Bob', 'Liz'), (4500.0, 6666.66, 9999.99)]</pre>
<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>
<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>
<h2>Method 2: Zip Function with Unpacking</h2>
<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>
<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]]
print(list(zip(*lst)))
</pre>
<p>This generates the list of tuples:</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="">[(0, 1, 2), ('Alice', 'Bob', 'Liz'), (4500.0, 6666.66, 9999.99)]</pre>
<p>I’d consider using the <code>zip()</code> function with unpacking the most Pythonic way to merge multiple lists into a list of tuples.</p>
<h2>Method 3: List Comprehension</h2>
<p>List comprehension is a compact way of creating lists. The simple formula is <code>[expression + context]</code>.</p>
<ul>
<li><strong>Expression</strong>: What to do with each list element?</li>
<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>
</ul>
<p>The example <code>[x for x in range(3)]</code> creates the list <code>[0, 1, 2]</code>. </p>
<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>
<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>
<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]
l1 = [1, 'Bob', 6666.66]
l2 = [2, 'Liz', 9999.99] print([(l0[i], l1[i], l2[i]) for i in range(len(l0))])</pre>
<p>The output produces the merged list of tuples:</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="">[(0, 1, 2), ('Alice', 'Bob', 'Liz'), (4500.0, 6666.66, 9999.99)]</pre>
<p>This method is short and efficient. It may not be too readable for you if you’re a beginner coder—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 “<a href="https://www.amazon.com/gp/product/B07ZY7XMX8" target="_blank" rel="noreferrer noopener">Python One-Liners</a>” (published with San Francisco Publisher NoStarch in 2020).</p>
<h2>Method 4: Simple Loop</h2>
<p>Sure, you can skip all the fancy Python and just use a simple loop as well! Here’s how this works:</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="">l0 = [0, 'Alice', 4500.00]
l1 = [1, 'Bob', 6666.66]
l2 = [2, 'Liz', 9999.99] lst = []
for i in range(len(l0)): lst.append((l0[i], l1[i], l2[i]))
print(lst)</pre>
<p>The output is the merged list of tuples:</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="">[(0, 1, 2), ('Alice', 'Bob', 'Liz'), (4500.0, 6666.66, 9999.99)]</pre>
<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’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’s going on in this code snippet. </p>
<p>You can visualize the execution of this code snippet in the interactive widget:</p>
<p> <iframe 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&codeDivHeight=400&codeDivWidth=350&cumulative=false&curInstr=0&heapPrimitives=nevernest&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false"> </iframe> </p>
<p><em><strong>Exercise</strong>: Click “Next” to see how the memory usage unfolds when running the code.</em></p>
<h2>Method 5: Enumerate</h2>
<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—for example, if you want to iterate over all indices of a list. In my opinion, it’s slightly better than using <code>range(len(l))</code>. Here’s how you can use <code>enumerate()</code> in your code to merge multiple lists into a single list of tuples:</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="">l0 = [0, 'Alice', 4500.00]
l1 = [1, 'Bob', 6666.66]
l2 = [2, 'Liz', 9999.99] lst = []
for i,x in enumerate(l0): lst.append((x,l1[i],l2[i]))
print(lst)</pre>
<p>The output is the list of tuples:</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="">[(0, 1, 2), ('Alice', 'Bob', 'Liz'), (4500.0, 6666.66, 9999.99)]</pre>
<p>Still not satisfied? Let’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>
<h2>Method 6: Map + Lambda</h2>
<p>With Python’s <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>
<ul>
<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…</li>
<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>
</ul>
<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’t know is that the <code>map()</code> function also allows multiple iterables. In this case, the lambda function takes multiple arguments—one for each iterable. It then creates an iterable of tuples and returns this as a result.</p>
<p>Here’s how you can create a list of tuples from a few given lists:</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="">l0 = [0, 'Alice', 4500.00]
l1 = [1, 'Bob', 6666.66]
l2 = [2, 'Liz', 9999.99] lst = list(map(lambda x, y, z: (x, y, z), l0, l1, l2))
print(lst)</pre>
<p>The output is the merged list of tuples:</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="">[(0, 1, 2), ('Alice', 'Bob', 'Liz'), (4500.0, 6666.66, 9999.99)]</pre>
<p>This is both an efficient and readable way to merge multiple lists into a list of tuples. The fact that it isn’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’t make this less beautiful. </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/06/...onic-ways/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016