views:

107

answers:

3

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 this 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?

+1  A: 

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.

unutbu
+5  A: 

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.

sdolan
+4  A: 

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.

John Percival Hackworth
The question was does `a_really_huge_fuction` get called more than once. This answer doesn't address that, so why the upvotes?
sdolan
I've clarified than answer. In the case of generators, the function is called once bu is executed in phases.
John Percival Hackworth
-1 -> +1. Thanks
sdolan