8

Is it possible that with the use of list comprehension to iterate through two variables at the same time increasing the loop position in both at the same time. See example below:

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

b = [6,7,8,9,10]

c = [i+j for i in a for j in b] # This works but the output is not what it would be expected.

expected output is c = [7, 9, 11, 13, 15] (n'th element from a + n'th element from b)

Thank you.

Eugene Lisitsky
  • 12,113
  • 5
  • 38
  • 59
Ignasi
  • 601
  • 2
  • 10
  • 23

1 Answers1

12
a = [1,2,3,4,5]
b = [6,7,8,9,10]

c = map(sum, zip(a, b))
print c

#Output
[7, 9, 11, 13, 15]
Jeremy
  • 818
  • 6
  • 19
  • 1
    While this is completely valid, using the sum function is unnecessarily complicated for a newbie. The other problem is that in Python 3 this returns a map object - e.g. `` While `map` is faster, the following is simpler... ```python c = [aa + bb for aa, bb in zip(a,b)] ``` – Diomedea Aug 27 '20 at 05:11