Python prints an incomplete list of a summation of two lists

Question:

I’m trying to calculate (and print) the summation of two lists, given in the code below

def a(list1, list2):
    rv = []
    for i in range(len(list1)):
        rv.append(list1[i] + list2[i])
        return rv
list1 = [1, 2]
list2 = [3, 4]
d = a(list1, list2)
print('rv =', d)

but the above print function only prints
rv = [4] which is only the zeroth entry of rv, I was expecting it to print rv = [4, 6]
Any suggestions?

Asked By: Ali Al Kayyali

||

Answers:

return rv must be de-indented out of the for loop, otherwise it will exit the function in the first iteration:

def a(list1, list2):
    rv = []
    for i in range(len(list1)):
        rv.append(list1[i] + list2[i])
    return rv

P.S. – your code can be simplified using zip and a list comprehension:

def a(list1, list2):
    return [a + b for a, b in zip(list1, list2)]

Answered By: The Thonnu
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.