Is there a way to test the return of a function in a list (or dict) comprehension? I'd like to avoid writing that:
lst = []
for x in range(10):
bar = foo(x)
if bar:
lst.append(bar)
and use a list comprehension instead. Obviously, I don't want to write:
[foo(x) for x in range(10) if foo(x)]
so?
[foo(x) for x in range(10) if ??? ]
List comprehensions cannot contain statements, only expressions. In fact, that's true for all expressions in Python: they can only contain other expressions. So, no, you can't put a return inside a list comprehension.
List comprehensions are used for creating new lists from other iterables. As list comprehensions return lists, they consist of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element.
Unlike with for loops, list comprehensions automatically put their output into a list. In the first snippet, we have to explicitly create a new list and then append to it inside the for loop. By contrast, in the second snippet we simply assign the output of the list comprehension to our new variable.
Answer: You can use any expression inside the list comprehension, including functions and methods.
How about
filter(None, map(foo, range(10)))
If you don't want to keep the intermediate list, replace map()
with itertools.imap()
. And with itertools.ifilter()
, the whole thing could be turned into a generator.
itertools.ifilter(None, itertools.imap(foo, range(10)))
Just make a generator to compute the values and build the filtered list from the generator afterwards.
Example:
# create generator via generator expression
results = (foo(x) for x in xrange(10))
# build result list, not including falsy values
filtered_results = [i for i in results if i]
For reference:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With