Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does sum function work in python with for loop [duplicate]

I was using sum function in python, and i am clear about it's general structure sum(iterable, start) , but i am unable to get the logic behind the following code

test = sum(5 for i in range(5) )
print("output:  ", test) 

output: 25

Please can anyone describe what is happening here, basically here 5 is getting multiplied with 5, and same pattern is there for every sample input.

like image 200
alok456 Avatar asked Jun 07 '26 19:06

alok456


1 Answers

Your code is shorthand for:

test = sum((5 for i in range(5)))

The removal of extra parentheses is syntactic sugar: it has no impact on your algorithm.

The (5 for i in range(5)) component is a generator expression which, on each iteration, yields the value 5. Your generator expression has 5 iterations in total, as defined by range(5). Therefore, the generator expression yields 5 exactly 5 times.

sum, as the docs indicate, accepts any iterable, even those not held entirely in memory. Generators, and by extension generator expressions, are memory efficient. Therefore, your logic will sum 5 exactly 5 times, which equals 25.

A convention when you don't use a variable in a closed loop is to denote that variable by underscore (_), so usually you'll see your code written as:

test = sum(5 for _ in range(5))
like image 96
jpp Avatar answered Jun 09 '26 09:06

jpp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!