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