Issue adding the some from two separate lists

I’m having trouble performing addition with two seperate lists. I can’t decide if I should be doing a nested list or not. I believe my logic is there. Find sum of list 1, find some of list 2, compare values, return bigger list.

Create a function named `larger_sum()` that takes two lists of numbers as parameters named `lst1` and `lst2` . The function should return the list whose elements sum to the greater number. If the sum of the elements of each list are equal, return `lst1` .

Here is my code:

``````#Write your function here

def larger_sum(lst1, lst2):
sum1 = 0
sum2 = 0
for i in lst1:
sum1 = sum1 + i
return sum1
for x in lst2:
sum2 = sum2 + x
return sum2
if sum1 > sum2:
return lst1
else:
return lst2
#Uncomment the line below when your function is done
print(larger_sum([1, 9, 5], [2, 3, 7]))
``````

Where possible please include a link to the lesson which the question relates to. It’s often very useful for others.

Please take note of what `return` does when it’s executed; it passes back that object reference and it exits the function.

1 Like

@tgrtim

I’m not sure why I’m having such a hard time with returns. But that seemed to be the issue. Here is my code. Albeit, inefficient it solved the problem.

``````#Write your function here

def larger_sum(lst1, lst2):
sum1 = 0
sum2 = 0
for i in lst1:
sum1 = sum1 + i
for x in lst2:
sum2 = sum2 + x
if sum1 > sum2:
return lst1
elif sum1 == sum2:
return lst1
else:
return lst2
#Uncomment the line below when your function is done
print(larger_sum([1, 9, 5], [2, 3, 7]))
``````
1 Like

Hello @jrb0831!

Here’s a brief summary on `return` in Python.

@jrb0831, your second post is much better compared to your first one, but I feel just to be on the safe side, you should use a variable to check which list you want to return, and then return such AFTER the if…else statement rather than doing it directly from the conditional… Seems much more cleaner and pythonic.

``````def larger_sum(lst1, lst2):
sum1 = 0
sum2 = 0
for i in lst1:
sum1 = sum1 + i
for x in lst2:
sum2 = sum2 + x
if sum1 >= sum2:
lst = lst1
else:
lst = lst2
return lst
#Uncomment the line below when your function is done
print(larger_sum([1, 9, 5], [2, 3, 7]))
``````

Hope this helped!

1 Like

@dr_victoria - thank you for the article!

I finally found some time to go through it. It simplifies what different scenarios returns occur in. Appreciate the help as always.

1 Like

@obidigbo - Understood, but is there any other advantage to this other than that it looks cleaner? Will it execute quicker?