Proposed new syntax

Steve D'Aprano steve+python at pearwood.info
Wed Aug 16 13:18:31 EDT 2017


On Wed, 16 Aug 2017 11:53 pm, jmp wrote:

> On 08/10/2017 04:28 PM, Steve D'Aprano wrote:
>> Every few years, the following syntax comes up for discussion, with some
>> people saying it isn't obvious what it would do, and others disagreeing and
>> saying that it is obvious. So I thought I'd do an informal survey.
>> 
>> What would you expect this syntax to return?
>> 
>> [x + 1 for x in (0, 1, 2, 999, 3, 4) while x < 5]
>> 
>> 
>> For comparison, what would you expect this to return? (Without actually
>> trying it, thank you.)
>> 
>> [x + 1 for x in (0, 1, 2, 999, 3, 4) if x < 5]
>> 
>> 
>> 
>> How about these?
>> 
>> [x + y for x in (0, 1, 2, 999, 3, 4) while x < 5 for y in (100, 200)]
>> 
>> [x + y for x in (0, 1, 2, 999, 3, 4) if x < 5 for y in (100, 200)]
>> 
>> 
>> 
>> Thanks for your comments!
>> 
> 
> [1,2,3]
> [1,2,3,4,5]
> SyntaxError("Have you tried Perl ?")
> SyntaxError("Have you tried Perl ?")
> 
> I really would not want to deal with 3 and 4.

:-)

#4 is actually valid syntax right now, and has been since Python 2.2.

py> [x + y for x in (0, 1, 2, 999, 3, 4) if x < 5 for y in (100, 200)]
[100, 200, 101, 201, 102, 202, 103, 203, 104, 204]


It is equivalent to:

for x in (0, 1, 2, 999, 3, 4):
    if x < 5:
        for y in (100, 200):
            x + y  # collect into the list


-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list