Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function inside list comprehension - is it evaluated multiple times [duplicate]

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 it evaluated once and cached ?

  1. y = [x*f(r) for x in xlist]

  2. c = f(r)

    y = [x*c for x in xlist]

where

def f(r):
    ... some arbitrary function ...
like image 570
dilbert Avatar asked May 27 '11 16:05

dilbert


People also ask

Does list comprehension create a copy?

List Comprehension. We can copy the elements from the list using list comprehension. Modifying the original_list won't be reflected in the copied_list and vice_versa. And also we can apply any function to each element in the list and copy it using list comprehension.

Is nested list comprehension faster than for nested loop?

As we can see, the for loop is slower than the list comprehension (9.9 seconds vs. 8.2 seconds). List comprehensions are faster than for loops to create lists. But, this is because we are creating a list by appending new elements to it at each iteration.

Can list comprehension return two values?

2 List Comprehension. This has two drawbacks: You can only look for one value at a time. It only returns the index of the first occurrence of a value; if there are duplicates, you won't know about them.

Is Python list comprehension faster than loop?

Because of differences in how Python implements for loops and list comprehension, list comprehensions are almost always faster than for loops when performing operations.


3 Answers

It evaluates for every iteration. Look at this:

>>> def f():
...     print("func")
... 
>>> [f() for i in range(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.

like image 68
utdemir Avatar answered Oct 12 '22 09:10

utdemir


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.

like image 28
Asgeir Avatar answered Oct 12 '22 10:10

Asgeir


Here is an easy way to find out:

>>> def f():
...     print "called"
...     return 1
...
>>> [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.

like image 10
Dave Kirby Avatar answered Oct 12 '22 09:10

Dave Kirby