-1
def sum_five(l):
    return sum(num for num in l if num > 5)
#desired outcome:
#sum_five([1, 5, 20, 30, 4, 9, 18]) ➞ 77
#sum_five([1, 2, 3, 4]) ➞ 0
#sum_five([10, 12, 28, 47, 55, 100]) ➞ 252

gotten this as a solution. The question is to loop through a list and sum up those that are less than 5. This is the cleanest and shortest answer which i really loved to learn. Can anyone explain in very simple English to me what does the num for num in l if num > 5 really means? And give me more examples to understand that logic so i can next time apply it? PS: i can do the outcome using for loop and if statement already, i just want to learn how to use this one liner. Thanks.

2 Answers2

0

This is known as Generator Expression which gives you another list which means like this:

FOR any element which we call it num, in the list which we call it l, if this element(num) is greater than 5, take it and put it in result list.

For example for [1,2,3,4] there is no number greater than 5, so the result is [] which has the summation equal to zero.

Another example is [1,5,20,30,4,9,18] which has the result equal to [20,30,9,18] which has the summation equal to 20+30+9+18 = 77

TheFaultInOurStars
  • 3,464
  • 1
  • 8
  • 29
-1

The list comprehension -- any list comprehension -- can be written as a for loop remembering that it returns a list (meaning you don't have to write the part that assigns the result to a list which in this case I've called out). That's a good thing because that list you are taking the sum of and returning that result instead.

out = []
def sum_five(l):
    for num in l:
        if num > 5:
            out.append(num)
        else:
            continue
    return sum(out)

The general form a list comprehension is worth going into more. But I'm going to strip out some of the code to this for clarity

for num in l:
        if num > 5:
            num

Goes to this:

for num in l if num > 5:
            num

And then to this:

num for num in l if num > 5:

We don't need that colon at the end and the whole thing gets put in braces because that's what specifies a list is getting returned. That leaves us with:

[num for num in l if num > 5]

You then take the sum of that list:

sum([num for num in l if num > 5])

You'll notice the formatting is a bit different than for the loop. If it was just a long no one would use it.

hrokr
  • 3,276
  • 3
  • 21
  • 39
  • The OP's case is not a list comprehension, it's a generator expression. You can tell by the lack of square brackets. – ShadowRanger Apr 04 '21 at 03:42
  • I understand what you're saying. But, from what I've noticed, new people often get things just plain wrong. The OP is saying they don't the basic logic. To me, that means a generator was not intended. And if turns out that was the case -- editing the question and answer will be in order. – hrokr Apr 04 '21 at 03:47