Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Produce list which is a sum of two lists, item-wise [duplicate]

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 'for' constructor? Like:

c = [aa+bb for aa in a for bb in b]

(which obviously returns not what I want)

like image 693
user1513100 Avatar asked Jul 09 '12 20:07

user1513100


2 Answers

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.

like image 162
Ashwini Chaudhary Avatar answered Sep 27 '22 21:09

Ashwini Chaudhary


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]
like image 23
stilldodge Avatar answered Sep 27 '22 22:09

stilldodge