[Python-ideas] filter-only list comps

Greg Ewing greg.ewing at canterbury.ac.nz
Fri Feb 26 01:11:10 CET 2010


Fred Drake wrote:

> I like this, but it has the same readability issue I noted for cases
> where decomposition is used:
> 
>     [(k, v) from somedict.items() if condition(v)]

I don't think that's too bad if you keep in mind that

   [x from stuff]

is a shorthand for

   [x for x in stuff]

whatever x happens to be. So your example would be
equivalent to

   [(k, v) for (k, v) in somedict.items() if condition(v)]

As a bonus, the short form could probably be made more
efficient, because the tuples produced by the for-loop
could be put straight into the result list, instead of
having to re-pack k and v into a new tuple.

-- 
Greg



More information about the Python-ideas mailing list