开发者

python: does `for i in obj.func()` re-run `func` every iteration?

开发者 https://www.devze.com 2023-01-16 08:40 出处:网络
let\'s say I have the following code: for a in object.a_really_huge_function(): print a In order to prevent a_really_huge_function from running multiple times, I am used to doing t开发者_如何学编程

let's say I have the following code:

for a in object.a_really_huge_function():
    print a

In order to prevent a_really_huge_function from running multiple times, I am used to doing t开发者_如何学编程his in other languages:

a_list = object.a_really_huge_function()
for a in a_list:
    print a

Is that necessary in Python? Will the part after in run on every single loop?


The python interpreter is your friend.

>>> def some_func():
...     print 'in some_func'
...     return [1, 2, 3, 10]
... 
>>> for a in some_func():
...     print a
... 
in some_func
1
2
3
10

In short, no, it gets called once.


You can also use generators to avoid returning huge results by relinquishing control after each step of the algorithm as follows:

def a_really_huge_fuction(huge_number):
    i = 0
    while i < huge_number:
        yield i   # Relinquishes control to caller, resume execution at next line
        i = i + 1

In this case, the function is called once, but has its execution spread over huge_number different times. See the yield documentation for more details.


It's not necessary.

for a in object.a_really_huge_function():

calls a_really_huge_function only once.

The only advantage of saving the result in a variable would be if you are calling the same function elsewhere in your code.

If the function returns a list, you might do better in terms of memory usage by making object.a_really_huge_function() return an iterator, but otherwise you are fine.

0

精彩评论

暂无评论...
验证码 换一张
取 消