How to use re match objects in a list comprehension


I have a function to pick out lumps from a list of strings and return them as another list:

def filterPick(lines,regex):
    result = []
    for l in lines:
        match =,l)
        if match:
            result += []
    return result

Is there a way to reformulate this as a list comprehension? Obviously it's fairly clear as is; just curious.

Thanks to those who contributed, special mention for @Alex. Here's a condensed version of what I ended up with; the regex match method is passed to filterPick as a "pre-hoisted" parameter:

import re

def filterPick(list,filter):
    return [ ( l, ) for l in list for m in (filter(l),) if m]

theList = ["foo", "bar", "baz", "qurx", "bother"]
searchRegex = re.compile('(a|r$)').search
x = filterPick(theList,searchRegex)

>> [('bar', 'a'), ('baz', 'a'), ('bother', 'r')]
3/14/2010 5:59:08 PM

Accepted Answer

[ for l in lines for m in [] if m]

The "trick" is the for m in [] part -- that's how you "assign" a value that you need to use more than once, within a list comprehension -- add just such a clause, where the object "iterates" over a single-item list containing the one value you want to "assign" to it. Some consider this stylistically dubious, but I find it practical sometimes.

3/12/2010 11:56:25 PM

return [ for m in (, l) for l in lines) if m]

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow