Capt.Pyrite
Capt.Pyrite

Reputation: 911

how to add one list with another list?

I want to add an list with another list this is what i mean i there is 2 lists and u want to add list1[0] with list2[0] obviously there will be more than just 1 values in the lists, also i get no erros.

my code:

list1 = [7,9,0,9,4,9]
list2 = [2,6,9,0,3,7]

for num1 in range(len(list1)):
  pass
pass

for num2 in range(len(list2)):
  x = list1[num1]+list2[num2]
  print(x)
pass

my output:

11
15
18
9
12
16

what my should be:

9
15
9
9
7
16

Upvotes: 1

Views: 96

Answers (3)

Soudipta Dutta
Soudipta Dutta

Reputation: 2152

Use zip(list1,list2) with List Comprehension.

list1 = [1, 2, 3]
list2 = [4, 5, 6]

list12 = [x+y for x,y in zip(list1,list2)]

print(list12)

Method 2 :

from  operator import add
aa = list(map(add,list1,list2))
print(aa)
Output   
[5, 7, 9]

Upvotes: 2

Aven Desta
Aven Desta

Reputation: 2443

>>> [sum(x) for x in zip(list1, list2)]

or

>>> from operator import add
>>> list( map(add, list1, list2) )

Upvotes: 2

Matheus Delazeri
Matheus Delazeri

Reputation: 445

You should use list1[num2] in line 9 instead list1[num1].

x = list1[num2]+list2[num2]
list1 = [7,9,0,9,4,9]
list2 = [2,6,9,0,3,7]

for num1 in range(len(list1)):
  pass
pass

for num2 in range(len(list2)):
  x = list1[num2]+list2[num2]
  print(x)
pass

Upvotes: 1

Related Questions