0

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]

2
  • 3
    Shoudn't your output be [5, 7, 9]? Commented Feb 16, 2018 at 17:43
  • Sorry I edited my post. Output should be` [5,7,9]`. But I am not getting it. Commented Feb 16, 2018 at 17:46

4 Answers 4

1
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]
Sign up to request clarification or add additional context in comments.

3 Comments

Oh my god. You guys are great. I was taking it challenge and spent more than 12 hrs to improve my python coding.
@user1586957 I'm not sure that writing longer (and presumably slower) code without using optimized built-in functions will improve your coding by much.
@DeepSpace Maybe he is "purist" or he is coming from a C or Assembly background.
1

try this,

a = [1,2,3]
b = [4,5,6]
c=list()
for i in range(len(a)):
    c.append(a[i]+b[i])

Comments

0

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()

Comments

0

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))  

2 Comments

You should really define c in your function, as it is not initialized within the scope of your function, so if something else added elements to it in another part of the code, the add_array function would return an incorrect result
Your answer is really a bad version of @chrisz answer and my own answer. There is no need to convert a and b explicitly to arrays (see my answer).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.