Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Zip With List Output Instead of Tuple | Most Pythonic Way

#1
Zip With List Output Instead of Tuple | Most Pythonic Way

<div><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>
<p><em>Intermediate Python coders know the <code>zip()</code> function. But if you’re like me, you’ve often cursed the output of the zip function: first of all, it’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>
<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 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>
</div>
</figure>
<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 – A Helpful Illustrated Guide to Nested Lists in Python"> of lists</a>?</p>
<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>
<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]
l2 = ['Alice', 'Bob', 'Ann', 'Liz']
# ... calculate result ...
# Output: [[1, 'Alice'], [2, 'Bob'], [3, 'Ann'], [4, 'Liz']]</pre>
<p>Here’s a quick overview of our solutions:</p>
<p> <iframe src="https://trinket.io/embed/python/07d4e000fe" width="100%" height="500" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> </p>
<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>
<h2>Method 1: Generator Expression</h2>
<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>
<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]
l2 = ['Alice', 'Bob', 'Ann', 'Liz'] # Method 1
zipped = list(list(x) for x in zip(l1, l2)) print(zipped)
# [[1, 'Alice'], [2, 'Bob'], [3, 'Ann'], [4, 'Liz']]</pre>
<p>This is efficient but not the most concise way of accomplishing this task.</p>
<h2>Method 2: List Comprehension</h2>
<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 — 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>
<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]
l2 = ['Alice', 'Bob', 'Ann', 'Liz'] # Method 2:
zipped = [list(x) for x in zip(l1, l2)] print(zipped)
# [[1, 'Alice'], [2, 'Bob'], [3, 'Ann'], [4, 'Liz']]
</pre>
<h2>Method 3: For Loop and Zip</h2>
<p>Coders who don’t like list comprehension and generator expressions (or, who don’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>
<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]
l2 = ['Alice', 'Bob', 'Ann', 'Liz'] # Method 3:
zipped = []
for t in zip(l1, l2): zipped.append(list(t)) print(zipped)
# [[1, 'Alice'], [2, 'Bob'], [3, 'Ann'], [4, 'Liz']]
</pre>
<p>This method is readable but less concise.</p>
<h2>Method 4: For Loop and Indexing</h2>
<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>
<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]
l2 = ['Alice', 'Bob', 'Ann', 'Liz'] # Method 4:
zipped = []
for i in range(len(l1)): zipped.append([l1[i], l2[i]]) print(zipped)
# [[1, 'Alice'], [2, 'Bob'], [3, 'Ann'], [4, 'Liz']]
</pre>
<p>However, this method is least Pythonic, lengthy, and it works only for equally-sized lists.</p>
<p><em><strong>Exercise</strong>: What happens if the first list has more elements than the second list?</em> </p>
<h2>Method 5: Zip() + Map() + List()</h2>
<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>
<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]
l2 = ['Alice', 'Bob', 'Ann', 'Liz'] # Method 5
print(list(map(list,zip(l1, l2))))
# [[1, 'Alice'], [2, 'Bob'], [3, 'Ann'], [4, 'Liz']]</pre>
<p>I don’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’s Article: “Fate of Reduce() in Python 3000”">disliked functional programming</a> as well.</p>
<h2>Discussion</h2>
<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>
<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/07/...honic-way/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016