Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Add Two Lists Element-wise in Python

#1
How to Add Two Lists Element-wise in Python

<div><div class="kk-star-ratings kksr-valign-top kksr-align-left " data-payload="{&quot;align&quot;:&quot;left&quot;,&quot;id&quot;:&quot;391288&quot;,&quot;slug&quot;:&quot;default&quot;,&quot;valign&quot;:&quot;top&quot;,&quot;reference&quot;:&quot;auto&quot;,&quot;count&quot;:&quot;0&quot;,&quot;readonly&quot;:&quot;&quot;,&quot;score&quot;:&quot;0&quot;,&quot;best&quot;:&quot;5&quot;,&quot;gap&quot;:&quot;5&quot;,&quot;greet&quot;:&quot;Rate this post&quot;,&quot;legend&quot;:&quot;0\/5 - (0 votes)&quot;,&quot;size&quot;:&quot;24&quot;,&quot;width&quot;:&quot;0&quot;,&quot;_legend&quot;:&quot;{score}\/{best} - ({count} {votes})&quot;}">
<div class="kksr-stars">
<div class="kksr-stars-inactive">
<div class="kksr-star" data-star="1" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="2" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="3" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="4" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="5" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
<div class="kksr-stars-active" style="width: 0px;">
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
</div>
<div class="kksr-legend"> <span class="kksr-muted">Rate this post</span> </div>
</div>
<p class="has-global-color-8-background-color has-background"><strong>Summary: </strong>The most pythonic approach to add two lists element-wise is to use <code>zip()</code> to pair the elements at the same positions in both lists and then add the two elements. Here’s a quick look at the solution: <code>[x + y <strong>for</strong> x, y <strong>in</strong> zip(li_1, li_2)]</code>. An alternate proposition to this without using zip: <code>[li_1[i]+li_2[i] for i in range(len(li_smaller))]</code></p>
<hr class="wp-block-separator has-alpha-channel-opacity" />
<h2><strong>Problem Formulation</strong></h2>
<p><strong>Problem Statement: </strong>Given two lists, how will you add the two lists element-wise?</p>
<p><strong>Example: </strong>Consider that you have the following lists:</p>
<pre class="wp-block-code"><code>Input:
li_1 = [2,4,6]
li_2 = [1,3,5] Expected Output:
[3,7,11]</code></pre>
<p><strong>Challenge: </strong>How will you perform an element-wise addition of the two lists as shown below:</p>
<figure class="wp-block-image size-full is-style-default"><img loading="lazy" width="634" height="156" src="https://blog.finxter.com/wp-content/uploads/2022/05/image-322.png" alt="" class="wp-image-391332" srcset="https://blog.finxter.com/wp-content/uploads/2022/05/image-322.png 634w, https://blog.finxter.com/wp-content/uplo...300x74.png 300w" sizes="(max-width: 634px) 100vw, 634px" /></figure>
<h2><strong>Solution 1: The Naive Approach</strong></h2>
<p><strong>Approach: </strong></p>
<ul>
<li>The basic solution to this problem is to find out the length of the smaller list. </li>
<li>Then use a for loop to iterate across all the items of each list. Note that the range of iteration will be determined by the length of the smaller list.</li>
<li> In every iteration, select an element from each list with the help of its index and then add them up. </li>
<li>You can store the output generated in each iteration within another list and finally display the resultant list as an output. </li>
</ul>
<p><strong>Code:</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=""># Given Lists
li_1 = [2, 4, 6]
li_2 = [1, 3, 5, 15]
res = [] # resultant list to store the output # Find the smaller list
li_smaller = li_1 if len(li_2) &gt; len(li_1) else li_2 for i in range(len(li_smaller)): # add each item from each list one by one res.append(li_1[i] + li_2[i])
print(res)</pre>
<p><strong>Output:</strong></p>
<pre class="wp-block-code"><code>[3, 7, 11]</code></pre>
<p>The above solution can further be compressed with the help of a <strong><a href="https://blog.finxter.com/list-comprehension/">list comprehension</a></strong>, as shown below:</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=""># Given Lists
li_1 = [2, 4, 6]
li_2 = [1, 3, 5, 15] # Find the smaller list
li_smaller = li_1 if len(li_2) &gt; len(li_1) else li_2 res = [li_1[i]+li_2[i] for i in range(len(li_smaller))]
print(res)</pre>
<p>Let’s try to understand the working principle behind the list comprehension used in the above snippet. </p>
<p>The first part is the <strong>expression. </strong>In the above snippet, <code>li_1[i]+li_2[i]</code> is the expression that denotes the element-wise addition of the two lists. The second part represents the <strong>context </strong>which represents the counter variable <code>i</code> that ranges from <em>0</em> until the length of the smaller list. It is basically keeping track of the index of each element in the lists. </p>
<h2><strong>Solution 2: Using <a href="https://blog.finxter.com/python-ziiiiiiip-a-helpful-guide/" target="_blank" rel="noreferrer noopener">zip</a> and List Comprehension</strong></h2>
<p><strong>Approach: </strong>A more pythonic solution to the given problem is to pass both the lists into the <code>zip()</code> method. This returns a tuple consisting of elements in pairs that are at the same position in each list. Once you get the pair of elements, you can simply add them up. All of this can be performed within a list comprehension.</p>
<p><strong>Code:</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="">li_1 = [2, 4, 6]
li_2 = [1, 3, 5, 15]
res = [x + y for x, y in zip(li_1, li_2)]
print(res) # OUTPUT: [3, 7, 11]</pre>
<p>An advantage of using this approach over the previous solution is not only is it a more pythonic way of adding the two lists, but it also eliminates the necessity to explicitly find out the length of the smaller list in case the two lists have different lengths.</p>
<p><strong>A Quick Recap to Zip():</strong></p>
<p class="has-background" style="background-color:#cbeaef">The&nbsp;<code>zip()</code>&nbsp;function takes an arbitrary number of&nbsp;iterables&nbsp;and aggregates them to a single iterable, a zip object. It combines the&nbsp;i-th&nbsp;values of each iterable argument into a tuple. Hence, if you pass two iterables, each tuple will contain two values. If you pass three iterables, each tuple will contain three values. For example, zip together lists&nbsp;<code>[1, 2, 3]</code>&nbsp;and&nbsp;<code>[4, 5, 6]</code>&nbsp;to&nbsp;<code>[(1,4), (2,5), (3,6)]</code>. <br /><strong>Read More: <a href="https://blog.finxter.com/python-ziiiiiiip-a-helpful-guide/">Python Zip — A Helpful Illustrated Guide</a></strong></p>
<p><strong><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f381.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" />Finding Sum of Two Lists Element-wise for list of lists</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="">li = [[1, 2, 3], [4, 5, 6]]
res = [a + b for a, b in zip(*li)]
print(res) # [5, 7, 9]</pre>
<h2><strong>Solution 3: Using <a href="https://blog.finxter.com/python-map/" target="_blank" rel="noreferrer noopener">map()</a> and add()</strong></h2>
<p><strong>Prerequisites:</strong></p>
<p><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f48e.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Python facilitates us with many predefined functions for numerous mathematical, logical, relational, bitwise etc operations. These functions are contained within the operator module. One such function is <code>add(a,b)</code>, which returns the result of the addition of the two arguments, i.e., <code>a+b</code>.</p>
<p><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f48e.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> The&nbsp;<code>map()</code>&nbsp;function transforms one or more iterables into a new one by applying a “transformator function” to the i-th elements of each iterable. The arguments are the<em>&nbsp;transformator function object</em>&nbsp;and&nbsp;<em>one or more iterables</em>. If you pass&nbsp;<strong><em>n</em>&nbsp;iterables</strong>&nbsp;as arguments, the transformator function must be an&nbsp;<strong><em>n</em>-ary function</strong>&nbsp;taking&nbsp;<strong><em>n</em></strong>&nbsp;input arguments. The return value is an iterable map object of transformed, and possibly aggregated, elements.</p>
<p><strong>Approach: </strong>Pass the input lists and the <code>add()</code> function within the built-in method <code>map()</code>. The <code>add()</code> method will simply add the elements of the two lists and then return an iterable. This iterable can then be converted to a list using the list constructor. </p>
<p><strong>Code:</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="">from operator import add
li_1 = [2, 4, 6]
li_2 = [1, 3, 5, 15]
res = list(map(add, li_1, li_2))
print(res)</pre>
<p><strong>Output:</strong></p>
<pre class="wp-block-code"><code>[3, 7, 11]</code></pre>
<p><strong><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f381.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" />Finding Sum of Two Lists Element-wise for Unknown Number of Lists of Same Length</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="">def sum_li(*args): return list(map(sum, zip(*args))) res = sum_li([1, 2, 3], [4, 5, 6], [7, 8, 9])
print(res) # [12, 15, 18]</pre>
<h2><strong>Method 4: Using zip_longest from Itertools</strong> Module</h2>
<p>Until now, all the solutions considered the length of the smaller list. What if you want to add the elements considering the length of the larger list. In other words, consider the following scenario:</p>
<p><strong>Given:</strong> </p>
<pre class="wp-block-code"><code>li_1 = [2, 4, 6]<br>li_2 = [1, 3, 5, 15]</code></pre>
<p><strong>Expected Output: </strong></p>
<pre class="wp-block-code"><code>[3, 7, 11, 15]</code></pre>
<p><strong>Approach: </strong>To deal with this scenario, you can use the <code>zip_longest</code> method of the itertools module. Not only will this method group the elements at the same position in each list, but it also allows you to take the remaining elements of the longer list into consideration. </p>
<ul>
<li>Pass the two lists within the <code>zip_longest()</code>&nbsp;function and assign <code>0</code> the <code>fillvalue</code>&nbsp;parameter. </li>
<li>If all the items from the smaller list get exhausted, then the remaining values will be filled by the value that has been assigned to the <code>fillvalue</code> parameter. </li>
<li>Finally, perform the addition of elements at the same position that have been paired by the <code>zip_longest</code> method using the <code>sum()</code> function.</li>
</ul>
<p><strong>Code: </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="">from itertools import zip_longest
li_1 = [2, 4, 6]
li_2 = [1, 3, 5, 15]
res = [sum(x) for x in zip_longest(li_1, li_2, fillvalue=0)]
print(res)</pre>
<p><strong>Output:</strong></p>
<pre class="wp-block-code"><code>[3, 7, 11, 15]</code></pre>
<h2><strong>Method 5: Using <a href="https://blog.finxter.com/numpy-tutorial/" target="_blank" rel="noreferrer noopener">Numpy</a></strong></h2>
<p>If you have <strong>two lists that have the same length</strong>, then using Numpy can be your best bet. There are two ways of implementing the solution that you need. Let’s have a look at them one by one:</p>
<h3><strong>The + Operator</strong></h3>
<p>You can simply create two numpy arrays from the two lists and then find their sum using the <strong>+</strong> operator. Easy peasy!</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="">import numpy as np
li_1 = [2, 4, 6]
li_2 = [1, 3, 5]
a = np.array(li_1)
b = np.array(li_2)
print(a+b) # [ 3 7 11]</pre>
<h3><strong>numpy.add</strong></h3>
<p>The alternate formulation to the above solution is to use the numpy.add() method instead of directly using the + operator. </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="">import numpy as np
li_1 = [2, 4, 6]
li_2 = [1, 3, 5]
res = np.add(li_1, li_2)
print(res) # [ 3 7 11]</pre>
<h2><strong>Conclusion</strong></h2>
<p>Phew! We unearthed a wealth of solutions to the given problem. Please feel free to use any solution that suits you. Here’s a general recommendation to use the above approaches:</p>
<ul>
<li>Using <code>zip</code> is probably the most pythonic approach when you have simple lists at your disposal.</li>
<li>In case you do not wish to use <code>zip</code>, you can simply use a list comprehension as discussed in the first solution.</li>
<li>For lists with different lengths, you may use the <code>zip_longest</code> method to solve your problem.</li>
</ul>
<p>Happy learning! <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f642.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
</div>


https://www.sickgaming.net/blog/2022/05/...in-python/
Reply



Forum Jump:


Users browsing this thread:
2 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016