The sum() function is used to add two lists using the index number of the list elements grouped by the zip() function. A zip() function is used in the sum() function to group list elements using index-wise lists. Let's consider a program to add the list elements using the zip function and sum function in Python.
append() adds the new elements as another list, by appending the object to the end. To actually concatenate (add) lists together, and combine all items from one list to another, you need to use the . extend() method.
The zip
function is useful here, used with a list comprehension.
[x + y for x, y in zip(first, second)]
If you have a list of lists (instead of just two lists):
lists_of_lists = [[1, 2, 3], [4, 5, 6]]
[sum(x) for x in zip(*lists_of_lists)]
# -> [5, 7, 9]
From docs
import operator
list(map(operator.add, first,second))
Default behavior in numpy.add
(numpy.subtract
, etc) is element-wise:
import numpy as np
np.add(first, second)
which outputs
array([7,9,11,13,15])
Assuming both lists a
and b
have same length, you do not need zip, numpy or anything else.
Python 2.x and 3.x:
[a[i]+b[i] for i in range(len(a))]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With