Element-Wise Sum of Lists with Lambda

Write a lambda function that takes two lists and returns a list that is the element-wise sum of the two lists.

Example 1:

Input: [1, 2, 3], [4, 5, 6]
Output: [5, 7, 9]

Example 2:

Input: [7, 8, 9], [1, 2, 3]
Output: [8, 10, 12]

Use a lambda function and the built-in map and add functions.

# Import the add function from the operator module
from operator import add

# Define the lambda function
element_wise_sum = lambda x, y: list(map(add, x, y))

# Test the function
print(element_wise_sum([1, 2, 3], [4, 5, 6])) # Output: [5, 7, 9]
print(element_wise_sum([7, 8, 9], [1, 2, 3])) # Output: [8, 10, 12]

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!