Understanding Python list with function as output and conditional

For some function that can return None or some other value and list of values:

def fn(x):
    if x == 4:
        return None
    else return x

lst = [1, 2, 3, 4, 5, 6, 7]

      

I want to have a list of outputs fn()

that do not return None

I have some code that works like this:

output = []
for i in lst:
    result = fn(i)
    if result:
        output.append(result)

      

I can express it as a list comprehension like this:

output = [fn(i) for i in lst if fn(i)]

      

but it runs fn(i)

on anything that doesn't return None

twice, which is undesirable if it's fn

an expensive feature.

Is there a way to have a good understanding of pythonic without executing the function twice?

Possible Solution:

output = [fn(i) for i in lst]
output = [o for o in f if o]

      

+3


source to share


2 answers


Your problem is what is being None

created by the function, not the one you are iterating over. Try



 output = [fi for fi in map(fn, lst) if fi is not None]

      

+4


source


Just combine your solutions:

[x for x in [fn(i) for i in lst] if x is not None]

      



The downside is that anything None

in the original list not created fn

will also be deleted.

+2


source







All Articles