[Newby question] List comprehension

Christopher T King squirrel at WPI.EDU
Fri Aug 6 16:11:16 CEST 2004

On Fri, 6 Aug 2004, Eelco Hoekema wrote:

> [(root, filter(song, files)) for (root, dir, files) in
> os.walk(os.path.abspath('.')) if filter(song, files)]
> Now, this will work. However, it seems kind of silly to call the filter
> twice. Is there a way to keep this in one list comprehension, but with
> just filtering once?

You may do best to split this into two LCs:

 temp = [(root, filter(song,files)) for (root, dir, files) in
 temp = [(root, songs) for (root, songs) in temp if songs]

Or if you prefer, replace the latter with:
 temp = filter(temp, lambda x: x[1])

Or even, in 2.4:
 temp = filter(temp, itemgetter(1))

In 2.4, you will also be able to replace the first LC with a generator 
expression, saving a bit of both memory and processor time (the change 
would consist of replacing the brackets with parentheses).

Hope this helps.

More information about the Python-list mailing list