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.
CodePudding user response:
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))
CodePudding user response:
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.