Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python transform and filter list with for / if

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]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading