[Python-ideas] Fwd: Fwd: unpacking generalisations for list comprehension

Michel Desmoulin desmoulinmichel at gmail.com
Fri Oct 14 05:16:01 EDT 2016


Regarding all those examples:

Le 14/10/2016 à 00:08, אלעזר a écrit :
> Trying to restate the proposal, somewhat more formal following Random832
> and Paul's suggestion.
>
> I only speak about the single star.
> ---
>
> *The suggested change of syntax:*
>
>     comprehension ::=  starred_expression comp_for
>
> *Semantics:*
>
> (In the following, f(x) must always evaluate to an iterable)
>
> 1. List comprehension:
>
>     result = [*f(x) for x in iterable if cond]
>
> Translates to
>
>     result = []
>     for x in iterable:
>         if cond:
>             result.extend(f(x))
>
> 2. Set comprehension:
>
>     result = {*f(x) for x in iterable if cond}
>
> Translates to
>
>     result = set()
>     for x in iterable:
>         if cond:
>             result.update(f(x))

Please note that we already have a way to do those. E.G:

    result = [*f(x) for x in iterable if cond]

can currently been expressed as:

    >>> iterable = range(10)
    >>> f = lambda x: [x] * x
    >>> [y for x in iterable if x % 2 == 0 for y in f(x)]
    [2, 2, 4, 4, 4, 4, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8, 8, 8, 8, 8]


Now I do like the new extension syntax. I find it more natural, and more 
readable:

    >>> [*f(x) for x in iterable if x % 2 == 0]

But it's not a missing feature, it's really just a (rather nice) 
syntaxic improvement.




More information about the Python-ideas mailing list