Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add SUM of values of two LISTS into new LIST

Tags:

python

list

sum

People also ask

How do you sum two lists in Python?

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.

How do you add all the elements of a list in a new list?

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))]