1

I found this simple code snippet from somewhere, but I don't understand how come this sum() syntax works.

total = sum(1 for _ in [1,2,3,4,5])
print(total)      # 5

for _ in [1,2,3,4,5] is nothing but the looping five times.

So the code snippet loops five times and add 1 for each loop so becomes 5 I guess.

I'm not sure about while looping five times in for _ in [1,2,3,4,5] what's happening then with 1?

According to the syntax of sum(iterable, start), the first argument should be iterable, but 1 is int. How come this works based on the sum syntax. How this code internally works? I'm confused.

user2761895
  • 1,431
  • 4
  • 22
  • 38
  • 1
    The entire statement `1 for _ in [1,2,3,4,5]` is the iterator. Remember, arguments are separated by commas `,` so you can tell that everything between the parentheses is a single argument. (The commas in the list literal don't count) – MattDMo Dec 17 '21 at 16:05
  • The values from the list are ignored, only its length serves the purpose, as it ensures there are 5 iterations. In each iteration you yield the value 1. You could also do it with `sum(1 for _ in "aaaaa")`, because only the length of the string is relevant. – trincot Dec 17 '21 at 16:18

2 Answers2

3

1 for _ in [1,2,3,4,5] is an iterator which is similar to

def my_gen():
    for _ in range(5):
        yield 1

This returns 1 five times. So the line can be written as

sum((1,1,1,1,1))
001
  • 13,291
  • 5
  • 35
  • 66
  • Thanks a lot !!! This is called generator expression ( just googled it ). Learned a new thing. – user2761895 Dec 17 '21 at 16:28
  • YW. A generator is a type of iterator. Read more about it here: [Difference between Python's Generators and Iterators](https://stackoverflow.com/a/28353158) – 001 Dec 17 '21 at 17:01
0

Does it help if you break it down:

(1 for _ in [1,2,3])

or even

[1 for _ in [1,2,3]]

works as counting the elements of the list. So providing the iterable the result of that expression ([1,1,1]) to the sum() is providing the expected result.

B.Kocis
  • 1,954
  • 20
  • 19