Python: how to add elements in two lists in one-to-one correspondence

created at 07-26-2021 views: 12

There are two lists with the same length. Now if you need to add the values in the lists one by one to get a new list.

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

Method 1

Use for loop list length, add each element to form a new list

list3=[]
for i in range(len(list1)):
    new_value=list1[i]+list2[i]
    list3.append(new_value)
print(list3)

Method 2

Use numpy's sum() function

import numpy as np
list3=np.sum([list1,list2],axis=0).tolist()
print(list3)

If only use np.sum(), the type of list3 you get is not list, but numpy.ndarray, so you need to use .tolist() to convert numpy.ndarray to list type

created at:07-26-2021
edited at: 07-26-2021: