How does sum function work in python with for loop

坚强是说给别人听的谎言 提交于 2021-02-10 03:56:29

问题


I was using sum function in pyhton, 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.


回答1:


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))



回答2:


You can add a list to the sum function so you can make something like this:

test = sum((1,23,5,6,100))
print("output:  ", test) 

And you get 135.

So with your "for loop" you get a list and put that list to the sum function and you get the sum of the list. The real sum function uses yield insight and use every value and sum them up.




回答3:


Basically, it is summing 5 repeativily for every "i" on range(5). Meaning, this code is equivalent to n*5, being n the size of range(n).



来源:https://stackoverflow.com/questions/53983152/how-does-sum-function-work-in-python-with-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!