Reputation: 147
I need solution to sum (addition) of each items of having same index. I find the solution using map, zip, list comprehension. Is there any solution defining function. My attempt:
a = [1,2,3]
b = [4,5,6]
def add(a,b):
for x in a:
return(x)
def add1(x,b):
for b in b:
return x + b
print (add(a,b))
Output from above is 1
which is wrong
Expected output :[5,7,9]
Upvotes: 0
Views: 118
Reputation: 11
You could use the code below to add if they have the same length
a = [1,2,3]
b = [4,5,6]
c=[]
def add_array(a,b):
for i in range(len(a)):
c.append(a[i]+b[i])
return c
print(add_array(a,b))
Or you could convert them to numpy arrays and add
import numpy as np
a = [1,2,3]
b = [4,5,6]
def add_array(a,b):
x=np.array(a)
y=np.array(b)
return x+y
print(add_array(a,b))
Upvotes: 0
Reputation: 1673
try this,
a = [1,2,3]
b = [4,5,6]
c=list()
for i in range(len(a)):
c.append(a[i]+b[i])
Upvotes: 1
Reputation: 8378
Using numpy
:
import numpy as np
c = np.add(a, b).tolist()
That is, you can define your function as:
def add(a, b):
return np.add(a, b).tolist()
or,
add = lambda a, b: np.add(a, b).tolist()
Upvotes: 0
Reputation: 51165
a = [1,2,3]
b = [4,5,6]
def add(a, b):
c = []
for i in range(len(a)):
c.append(a[i] + b[i])
return c
print(add(a, b))
Output:
[5, 7, 9]
Upvotes: 1