Python Add 2 Lists (Arrays) in Python

Question:

How can i add 2 numbers in a List.

I am trying to add 2 numbers in an array, it just shows None on the response box.
The code is looking thus :

def add2NumberArrays(a,b):
    res = []
    for i in range(0,len(a)):
        return res.append(a[i] + b[i])


a = [4,4,7]
b = [2,1,2]

print(add2NumberArrays(a,b))

Why does this return none? Please help.

Edits

My code looks thus :

def add2NumberArrays(a,b):
    for i in range(0,len(a)):
        res = []
        ans = res.append(a[i]+b[i])
    return ans

a = [4,4,7]
b = [2,1,2]

print(add2NumberArrays(a,b))
Asked By: Mike

||

Answers:

You can use itertools.zip_longest to handle different length of two lists.

from itertools import zip_longest
def add2NumberArrays(a,b):
    # Explanation: 
    # list(zip_longest(a, b, fillvalue=0))
    # [(4, 2), (4, 1), (7, 2), (0, 2)]
    return [i+j for i,j in zip_longest(a, b, fillvalue=0)]
    

a = [4,4,7]
b = [2,1,2,2]

print(add2NumberArrays(a,b))
# [6, 5, 9, 2]

Your code need to change like below:

def add2NumberArrays(a,b):
    res = []
    for i in range(0,len(a)):
        res.append(a[i]+b[i])
    return res

    # As a list comprehension
    # return [a[i]+b[i] for i in range(0,len(a))]


a = [4,4,7]
b = [2,1,2]

print(add2NumberArrays(a,b))
# [6, 5, 9]
Answered By: I'mahdi
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.