Proposed new syntax

Serhiy Storchaka storchaka at gmail.com
Fri Aug 11 08:48:36 EDT 2017


10.08.17 17:28, Steve D'Aprano пише:
> 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]

I would expect it to be equivalent to the following code:

     result = []
     for x in (0, 1, 2, 999, 3, 4):
         while x < 5:
             result.append(x + 1)

This is an infinite loop.

> 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]

     result = []
     for x in (0, 1, 2, 999, 3, 4):
         if x < 5:
             result.append(x + 1)

> How about these?
> 
> [x + y for x in (0, 1, 2, 999, 3, 4) while x < 5 for y in (100, 200)]

     result = []
     for x in (0, 1, 2, 999, 3, 4):
         while x < 5:
             for y in (100, 200):
                 result.append(x + y)

> [x + y for x in (0, 1, 2, 999, 3, 4) if x < 5 for y in (100, 200)]

     result = []
     for x in (0, 1, 2, 999, 3, 4):
         if x < 5:
             for y in (100, 200):
                 result.append(x + y)




More information about the Python-list mailing list