![]() |
|
[Tut] How to Add Two Lists Element-wise in Python - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] How to Add Two Lists Element-wise in Python (/thread-99498.html) |
[Tut] How to Add Two Lists Element-wise in Python - xSicKxBot - 06-03-2022 How to Add Two Lists Element-wise in Python Rate this post Summary: The most pythonic approach to add two lists element-wise is to use Code: zip()Code: [x + y for x, y in zip(li_1, li_2)]Code: [li_1[i]+li_2[i] for i in range(len(li_smaller))][b]Problem Formulation[/b] Problem Statement: Given two lists, how will you add the two lists element-wise? Example: Consider that you have the following lists: Code: Input:
li_1 = [2,4,6]
li_2 = [1,3,5] Expected Output:
[3,7,11]Challenge: How will you perform an element-wise addition of the two lists as shown below: ![]() [b]Solution 1: The Naive Approach[/b] Approach:
Code: Code: # 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) > 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)Output: Code: [3, 7, 11]The above solution can further be compressed with the help of a list comprehension, as shown below: Code: # 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) > len(li_1) else li_2 res = [li_1[i]+li_2[i] for i in range(len(li_smaller))]
print(res)Let’s try to understand the working principle behind the list comprehension used in the above snippet. The first part is the expression. In the above snippet, Code: li_1[i]+li_2[i]Code: i[b]Solution 2: Using zip and List Comprehension[/b] Approach: A more pythonic solution to the given problem is to pass both the lists into the Code: zip()Code: Code: 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]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. A Quick Recap to Zip(): The Code: zip()Code: [1, 2, 3]Code: [4, 5, 6]Code: [(1,4), (2,5), (3,6)]Read More: Python Zip — A Helpful Illustrated Guide Finding Sum of Two Lists Element-wise for list of listsCode: li = [[1, 2, 3], [4, 5, 6]]
res = [a + b for a, b in zip(*li)]
print(res) # [5, 7, 9]Prerequisites: 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: a+b The Code: map()Approach: Pass the input lists and the Code: add()Code: map()Code: add()Code: Code: 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)Output: Code: [3, 7, 11] Finding Sum of Two Lists Element-wise for Unknown Number of Lists of Same LengthCode: 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]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: Given: Code: li_1 = [2, 4, 6]li_2 = [1, 3, 5, 15]Expected Output: Code: [3, 7, 11, 15]Approach: To deal with this scenario, you can use the Code: zip_longest
Code: Code: 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)Output: Code: [3, 7, 11, 15]If you have two lists that have the same length, 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: [b]The + Operator[/b] You can simply create two numpy arrays from the two lists and then find their sum using the + operator. Easy peasy! Code: 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]The alternate formulation to the above solution is to use the numpy.add() method instead of directly using the + operator. Code: 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]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:
Happy learning!
|