7
votes

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 ??? ]
2
Why don't you want to use the first way? It's the appropriate way. - Rohit Jain
@Rohit Jain -- depending on foo, it could be an expensive operation which you don't want to do twice. - mgilson
@mgilson: And in the first example, he only does it once. - Tim Pietzcker
@TimPietzcker -- Ahh... I thought Rohit was refering to the first list-comprehension... I'm following the comment stream now. Thanks. - mgilson
@TimPietzcker.. Yeah I was talking about 1st list comprehension only. - Rohit Jain

2 Answers

10
votes

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)))
5
votes

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: