-2

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))
Mike
  • 167
  • 2
  • 10
  • 1
    Because the return of the `append` function is `None`. set `return res` out of the `for-loop`. – I'mahdi Dec 04 '22 at 19:51
  • @I'mahdi no it does not work. gives another Error . Please see edits/ – Mike Dec 04 '22 at 19:58
  • @Mike, set `res = []` out of the `for-loop`. – I'mahdi Dec 04 '22 at 20:00
  • @l'mahdi gives me this now as Error "inconsistent use of tabs and spaces in indentation" – Mike Dec 04 '22 at 20:02
  • There are two distinctive issues in your (new) code: 1. `list.append` returns None. The list itself is modified in place. 2. You declare your list variable inside the loop, thus overwriting the work done during the previous iteration each time and ending the loop with a list of size 1. – Whole Brain Dec 04 '22 at 20:03
  • Is this Leetcode problem - https://leetcode.com/problems/add-two-numbers/? – Daniel Hao Dec 04 '22 at 20:20
  • @DanielHao not this one – Mike Dec 04 '22 at 20:25

1 Answers1

0

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]
I'mahdi
  • 23,382
  • 5
  • 22
  • 30
  • the second one worked fine for me in my case. I am just learning Data structures and Algorithms, so i am trying to familiarise with some questions i have seen once... Thanks for the tip – Mike Dec 04 '22 at 20:09