0

So im pretty new to programming so sorry for my relatively very low understanding of python in general.

Say i have 2 lists, A and B. If in some case i need to add numbers between 2 lists, each number adding to the number in the same position in the second list. Is there any simple way of doing so? Eg. A = [1, 2, 3] B = [4, 5, 6] so C = [1+4, 2+5, 3+6]

All I thought of so far being pretty tired is just adding the 2 but it just makes a list of items from A, followed by items from B

A = [1, 2, 3]
B = [4, 5, 6]
C = A + B

I'm trying to get C = [5, 7, 9] but it ends up being C = [1, 2, 3, 4, 5, 6] I understand why this would be but being new to this i have no clue of how to do this properly

Leo A
  • 3
  • 1
  • duplicate: answer here: https://stackoverflow.com/questions/25640628/python-adding-lists-of-numbers-with-other-lists-of-numbers – Clay Feb 02 '19 at 22:15

2 Answers2

1

With that, you are concatenating the two lists, not performing element-wise addition. To do what you have to do, you have a few different options. This is my preferred method:

from operator import add

list(map(add, A, B))

A list comprehension would also work:

[sum(x) for x in zip(A, B)]
iz_
  • 15,923
  • 3
  • 25
  • 40
0

Using numpy will also work.

import numpy as np
A = [1, 2, 3] 
B = [4, 5, 6] 
C = (np.array(A) + np.array(B)).tolist()
Clay
  • 2,584
  • 1
  • 28
  • 63