7

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 ??? ]
Adrien
  • 125
  • 1
  • 6

2 Answers2

10

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)))
NPE
  • 486,780
  • 108
  • 951
  • 1,012
5

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:

moooeeeep
  • 31,622
  • 22
  • 98
  • 187