I am trying to pass each element of foo_list into a function expensive_call, and get a list of all the items whose output of expensive_call is Truthy. I am trying to do it with list comprehensions, is it possible? Something like:
Something like this:
result_list = [y := expensive_call(x) for x in foo_list if y]
or....
result_list = [y for x in foo_list if y := expensive_call(x)]
Note: This is not a solution because it call expensive call twice:
result_list = [expensive_call(x) for x in foo_list if expensive_call(x)]
And before someone recommends none list comprehension, I know one can do:
result_list = []
for x in foo_list:
result = expensive_call(x)
result and result_list.append(result)
[x for x in foo_list if expensive_call(x)]? What's the difficulty? (That corresponds to the code in your non-comprehension version, too.)[y for y in map(expensive_call,foo_list) if y]result and result_list.append(x), useif result: result_list.append(x), idiomatic Python values clarity and being explicit, not brevityresult and result_list.append(result). Though as @juanpa.arrivillaga says, that's "cutesy" and could mislead many.