Skip to content Skip to sidebar Skip to footer

Python: Produce List Which Is A Sum Of Two Lists, Item-wise

Say I have two lists: a=[1,2,3,4,5] b=[5,4,3,2,1] I want to create a third one which will be linear sum of two given: c[i]==a[i]+b[i] c==[6,6,6,6,6] Is it possible to do with 'f

Solution 1:

Use zip():

>>> a = [1,2,3,4,5]
>>> b = [5,4,3,2,1]
>>> c = [x+y for x,y in zip(a, b)]
>>> c
[6, 6, 6, 6, 6]

or:

>>> c = [a[i] + b[i] for i in range(len(a))]
>>> c
[6, 6, 6, 6, 6]

c = [aa+bb for aa in a for bb in b] is something like:

 for aa in a:
     for bb in b:
           aa+bb

this means , select 1 from a and then loop through all elements of b while adding them to 1, and then choose 2 from a and then again loop through all values of b while adding them to 2, that's why you were not getting expected output.


Solution 2:

a=[1,2,3,4,5]
b=[5,4,3,2,1]

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

OR

map(lambda x,y:x+y, a, b)
[6, 6, 6, 6, 6]

Solution 3:

[ay + be for ay, be in zip(a, b)]

Solution 4:

 sums =   [a[i]+b[i] for i in range(len(a))]

Solution 5:

I don't know what you're trying to do, but you can easily do what you've asked with numpy. I'm just not sure you really want to add that extra dependency to your code.


Post a Comment for "Python: Produce List Which Is A Sum Of Two Lists, Item-wise"