Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list comprehension: test function return

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 ??? ]
like image 535
Adrien Avatar asked Nov 29 '12 18:11

Adrien


People also ask

Can you return a list comprehension Python?

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.

What do list comprehensions return?

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.

Does list comprehension always return list?

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.

Can we use function in list comprehension?

Answer: You can use any expression inside the list comprehension, including functions and methods.


2 Answers

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)))
like image 126
NPE Avatar answered Oct 01 '22 17:10

NPE


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:

  • https://docs.python.org/3/glossary.html#term-generator
  • https://wiki.python.org/moin/Generators
  • https://www.python.org/dev/peps/pep-0289/
like image 29
moooeeeep Avatar answered Oct 01 '22 15:10

moooeeeep