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 ??? ]
How about
If you don't want to keep the intermediate list, replace
map()
withitertools.imap()
. And withitertools.ifilter()
, the whole thing could be turned into a generator.Just make a generator to compute the values and build the filtered list from the generator afterwards.
Example:
For reference: