Skip to content Skip to sidebar Skip to footer

Function Inside List Comprehension - Is It Evaluated Multiple Times

Which one's a better way of doing list comprehension in python (in terms of computation time & cpu cycles). In example (1) is the value f(r) evaluated in each iteration or is

Solution 1:

It evaluates for every iteration. Look at this:

>>> deff():
... print("func")
... >>> [f() for i inrange(4)]
func
func
func
func
[None, None, None, None]

As you say, if f() has no side effects, storing the return value on a variable and using that variable instead is a lot faster solution.

Solution 2:

I would probably choose the latter because the Python compiler doesn't know if the function has side-effects so it is called for each element.

Solution 3:

Here is an easy way to find out:

>>>deff():...print"called"...return1...>>>[1+f() for x in xrange(5)]
called
called
called
called
called
[2, 2, 2, 2, 2]

so yes, if the function is going to be the same each time then it is better to call it once outside the list comprehension.

Solution 4:

The function f will be called for every element.

Solution 5:

It is very complex for the compiler/interpreter to determine that the function need not to be called many times. It is then very probable that the function is called many times. Thus, using the second solution is always the best solution.

Post a Comment for "Function Inside List Comprehension - Is It Evaluated Multiple Times"