Reputation: 37
for example
list1=[1,2,3,4,5]
list2=[1,2,3,4,5]
..
list3=[2,4,6,8,10]
I've already tried something, but it pops me a message that says: out of range". here is my code:
for i in range(mikos):
lista3[i]=lista1[i]+lista2[i]
print(lista3)
#'mikos' is the number of elements in each list
Upvotes: 2
Views: 118
Reputation: 910
One way is to do:
from operator import add
map(add, list1, list2)
Another would be:
[x + y for x, y in zip(list1, list2)]
And yet another one is
[sum(x) for x in zip(list1, list2)]
Upvotes: 1
Reputation: 5261
You can do this without a loop:
lista3 = [x+y for x,y in zip(lista1, lista2)]
Upvotes: 2
Reputation: 28648
Very simple approach is:
list1=[1,2,3,4,5]
list2=[1,2,3,4,5]
list3 = []
mikos = len(list1)
for i in range(mikos):
list3.append(list1[i]+list2[i])
print(list3)
Upvotes: 1