Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python prints an empty array of a summation of two lists

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading