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

Chris Angelico rosuav at gmail.com
Tue Mar 8 15:52:25 EST 2016


On Wed, Mar 9, 2016 at 7:46 AM, Mark Mollineaux
<bufordsharkley at gmail.com> wrote:
> This map-then-filter shortcoming is one of the most common warts I encounter
> with python syntax, and I would absolutely love an improvement here.
>
> I think ChrisA is closest with:
>
>> I'm really not liking the proposed syntax, but maybe there's an
>> alternative. My first thought on reading this proposal is: "Ah, it's like
>> SQL's 'HAVING' keyword". The trouble is that SQL can identify its columns,
>> but Python doesn't have an easy syntax for "the thing you're about to
>> return". Something like:
>>
>> [abs(x) for x in numbers having _ > 5]
>
> But I wonder, why not just:
>
> [abs(x) for x in numbers if _ > 5]
>
> Where _ refers to the return expression within a comprehension, and is
> interpreted specially in this context?

That makes it somewhat magical; compare these two conditions:

[(base//x) % 10 for x in numbers if x if _]

The first one MUST be filtered prior to mapping (else you'll get a
ZeroDivisionError), but the second has to be filtered afterwards.
Putting the two conditions into one comprehension might not be common,
but it's a bit odd to have them mean different things.

ChrisA


More information about the Python-ideas mailing list