Alex Rivera | Logout

How do I efficiently filter computed values within a Python list comprehension?

Asked 2008-09-24T22:08:57.363
24

The Python list comprehension syntax makes it easy to filter values within a comprehension. For example:

result = [x**2 for x in mylist if type(x) is int]

Will return a list of the squares of integers in mylist. However, what if the test involves some (costly) computation and you want to filter on the result? One option is:

result = [expensive(x) for x in mylist if expensive(x)]

This will result in a list of non-"false" expensive(x) values, however expensive() is called twice for each x. Is there a comprehension syntax that allows you to do this test while only calling expensive once per x?

Edit
Report

1 Answer

7

The most obvious (and I would argue most readable) answer is to not use a list comprehension or generator expression, but rather a real generator:

def gen_expensive(mylist):
    for item in mylist:
        result = expensive(item)
        if result:
            yield result

It takes more horizontal space, but it's much easier to see what it does at a glance, and you end up not repeating yourself.

answered 2008-09-24T22:24:42.163

Your Answer