milesma milesma - 3 months ago 7
Python Question

What is the python way to iterate two list and compute by position?

What is the Pythonic way to iterate two list and compute?

a, b=[1,2,3], [4,5,6]
c=[]
for i in range(3):
c.append(a[i]+b[i])
print(c)
[5,7,9]


Is there a one-liner for
c
without a for loop?

Answer

Use zip and list comprehension:

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