How else do I shorten this function's body which returns the list with the greatest sum into one line?

I can do it by resorting to unusual syntax which I only know through googling lol:

def larger_sum(lista, listb):
        return lista if sum(lista) >= sum(listb) else listb

lista = [2, 4, 5, 100, 20, 30, 40, 20, 80]
listb = [1, 4, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

print(larger_sum(lista, listb))

But is there a cleverer way of returning the list with the greatest sum in one line? I think there must be because the course hasn’t taught weird if else syntax yet iirc (haven’t got the greatest memory though and my brain is currently mush).
It is this exercise, and note that if both lists have the same sum then the first list needs to be returned:
https://www.codecademy.com/courses/learn-python-3/articles/advanced-python-code-challenges-loops

Hi!

I wouldn’t look for clever per se. A lot of one-liners are often either hard to read or not great for performance speed. The latter issue being potentially really bad.

That being said this does have a simple method in python (and many other languages) called max.

max(a,b) returns the value of the larger of the 2 values. What this exercises is doing is I guess making you write what the max() method would look like on the inside. (Also note, your return value is slightly incorrect in the else clause).

For this particular scenario, max() or sum() are ok. Maybe it’s useful to note that either method has to cycle through all your elements in your arrays, so it’s going to do as much work as the length of your arrays (n+m). If you knew you wanted to use sums often, you could keep tabs on what the array sums are as you insert items in and and take them out. So in this case if you looked for the max sum of your arrays, you’re just comparing 2 numbers instead of going through n+m items (size of your 2 arrays). So if you had the choice between updating values to keep track, it’s significantly more efficient to go that route. Which is why context always matters :slight_smile: !

What’s wrong with the return value in the else statement? I entered a bunch of different arguments and the function returned the correct list every time.

And yea that makes a lot of sense. Think they got me to write this function just as an exercise.

Ah my bad, I misread this as returning the largest size between the two lists, not returning the lists… Need more coffee :joy::joy::sob: