Search code examples
pythonpython-3.xgenerator-expression

Generator expression including conditional test without calling a function twice?


Suppose I have a function which performs some heavy calculations.

def f(x):
    ... 
    return result

Then I have a list with values I want to pass to f():

my_list = [2, 98, 4, 34, 23, 11]

I would like to find the first element x in this list which validates a condition on f(x) (let's say for example f(x) != 0), and get this computed result.

Basically, I would write a for loop like this:

def first_match(my_list):
    for x in my_list:
        r = f(x)
        if r != 0:
            return r

I would like to know if there is a way to get the same result using a generator expression?

What I thought so far was something like this:

r = next(f(x) if f(x) != 0 for x in my_list)

The issue is that this calls f() twice.


Solution

  • You can use a nested generator expression to avoid the double function call:

    next(y for y in (f(x) for x in my_list) if y != 0)