[Python-ideas] FW: Map-then-filter in comprehensions

Chris Angelico rosuav at gmail.com
Tue Mar 8 13:27:13 EST 2016


On Wed, Mar 9, 2016 at 4:26 AM, Ethan Furman <ethan at stoneleaf.us> wrote:
> On 03/08/2016 06:59 AM, Émanuel Barry wrote:
>
>> The general concept is name binding, so if I see something like
>>
>> [x for x, y in some_iterable as y > 5]
>>
>> I’m going be confused by what sort of name binding it does.
>
>
> I think everyone would be confused because that code is wrong:  it's
> assigning the `iterable` as `y`, and then comparing that to the value `5`.
>
> More realistic (and correct ;) might be:
>
> [z for x, y in some_iterable if x+y as z > 10]
>
> and the result is a list of numbers whose combined value is greater than 10.
>
> A name binding is in fact occuring, so `as` is a fine choice.

Implement that, and people will ask why they can't then unroll that:

def <listcomp>():
    result = []
    for x, y in some_iterable:
        if x+y as z > 10: # SyntaxError
            result.append(z)
    return z

I'm not sure people want name bindings in general expressions (note
that this can't be a feature of the 'if' statement, as it's capturing
and then continuing on), but as I see it, that's the only consistent
way to do what you're attempting there.

ChrisA


More information about the Python-ideas mailing list