[Python-ideas] filter-only list comps

Stefan Behnel stefan_ml at behnel.de
Fri Feb 26 14:47:38 CET 2010


Stephen J. Turnbull, 26.02.2010 04:28:
> Greg Ewing writes:
> 
>  >    [x from stuff]
>  > 
>  > is a shorthand for
>  > 
>  >    [x for x in stuff]
> 
> Any time you say "shorthand" you're probably violating TOOWTDI. :-)

Absolutely, so I would expect this to have zero change to make it in.


>  > 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.
> 
> This is a straightforward optimization that should be done anyway,
> though, if it isn't done already.

That's a good idea. Note, however, that the item extracted from the
iterable is not necessarily a tuple:

    >>> l = [[1,2], [3,4]]
    >>> [ (x,y) for (x,y) in l]
    [(1, 2), (3, 4)]

So the tuple packing may or may not be required, but that can only be
decided at runtime.

Stefan




More information about the Python-ideas mailing list