codesung codesung - 4 years ago 141
Python Question

How to sum element wise in python

Hello I am very new to programming.

I have two lists.

Code:

first_list = [1,90,55,20]
second_list = [99,10,45,80]

sumList=[]

for x,y in enumerate(first_list,second_list):
sumList.append(x+y)

print sumList


Expected output:

[100, 100, 100, 100]


but it is showing error:

TypeError: 'list' object cannot be interpreted as an index


Please help me and what is the fastest and easiest way to do this

Answer Source

You must use zip instead of enumerate

first_list = [1,90,55,20]
second_list = [99,10,45,80]

sumList=[]

for x,y in zip(first_list,second_list):
    sumList.append(x+y)

print sumList

One liner answer:

c = [x+y for x,y in zip(a, b)]

Other better way to do this are :

Use map with operator.add:

>>> from operator import add
>>> map(add, list1, list2)
[100, 100, 100, 100]

or zip with a list comprehension:

>>> [sum(x) for x in zip(list1, list2)]
[100, 100, 100, 100]

If you need to handle lists of different sizes, worry not! The wonderful itertools module does this.

>>> from itertools import zip_longest
>>> list1 = [1,2,1]
>>> list2 = [2,1,2,3]
>>> [sum(x) for x in zip_longest(list1, list2, fillvalue=0)]
[3, 3, 3, 3]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download