Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function in Python list comprehension, don't eval twice

I'm composing a Python list from an input list run through a transforming function. I would like to include only those items in the output list for which the result isn't None. This works:

def transform(n):
    # expensive irl, so don't execute twice
    return None if n == 2 else n**2


a = [1, 2, 3]

lst = []
for n in a:
    t = transform(n)
    if t is not None:
        lst.append(t)

print(lst)
[1, 9]

I have a hunch that this can be simplified with a comprehension. However, the straighforward solution

def transform(n):
    return None if n == 2 else n**2


a = [1, 2, 3]
lst = [transform(n) for n in a if transform(n) is not None]

print(lst)

is no good since transform() is applied twice to each entry. Any way around this?

like image 295
Nico Schlömer Avatar asked Jun 02 '26 14:06

Nico Schlömer


1 Answers

Use the := operator for python >=3.8.

lst = [t for n in a if (t:= transform(n)) is not None]
like image 169
Plagon Avatar answered Jun 06 '26 07:06

Plagon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!