Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python transform and filter list with for / if

Tags:

python

Is there a way to both transform and filter in a single list comprehension, i.e.:

def transform(el):
    if some_condition(el):
        return None

    return complex_logic(el)

def main():
    transformed = [transform(el) for el in some_list if transform(el) != None]

but avoid calling transform twice? I.e. assign it to a variable, something like (in pseudo-Python):

def main():
  transformed = [transformed for el in some_list let transformed = transform(el) if transformed != None]
like image 294
levant pied Avatar asked Jul 03 '26 02:07

levant pied


1 Answers

Since Python 3.8 you can use walrus operator :=:

def main():
    return [res for el in some_list if (res := transform(el)) is not None]

This way the result of calling to the transform function is stored in res then you can use it in the expression part of your list comprehension.

like image 162
SorousH Bakhtiary Avatar answered Jul 05 '26 16:07

SorousH Bakhtiary