how do I add 2 lists element-wise in python?
- User
how do I add 2 lists element-wise in python?
- Assistant
You can add two lists element-wise in Python using a combination of the
zip()function and list comprehension. Here's how you can do it:list1 = [1, 2, 3] list2 = [4, 5, 6] sum_list = [a + b for a, b in zip(list1, list2)] print(sum_list)In this code,
zip(list1, list2)returns an iterator of tuples where the first item in each passed iterator is paired together, and then the second item in each passed iterator are paired together etc.Then, list comprehension is used to iterate over the
zipobject to add the corresponding elements of the lists.When you run this code, it will output:
[5, 7, 9].Please note that this will only add up to the length of the shorter list if the lists are of unequal length. If you want to handle lists of unequal length and fill missing values with zeroes, you would need a more advanced approach, such as using .
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.