Proposed new syntax

Tim Chase python.list at tim.thechases.com
Sat Aug 12 09:20:39 EDT 2017


On 2017-08-11 00:28, Steve D'Aprano wrote:
> What would you expect this syntax to return?
> 
> [x + 1 for x in (0, 1, 2, 999, 3, 4) while x < 5]

[1, 2, 3]

I would see this "while-in-a-comprehension" as a itertools.takewhile()
sort of syntactic sugar:

>>> [x + 1 for x in takewhile(lambda m: m < 5, (0,1,2,999,3,4))]
[1, 2, 3]



> For comparison, what would you expect this to return?
[snip]
> [x + y for x in (0, 1, 2, 999, 3, 4) while x < 5 for y in (100,
> 200)]

This one could make sense as either

[100, 200, 101, 201, 102, 202]

or

[100, 101, 102]

(I think the default evaluation order of nested "for"s in a
comprehension would produce the former rather than the latter)

Thus it would be good to define behavior for both of these cases:

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

vs.

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

-tkc



Things would get even weirder when you have nested loopings like
that and one of the sources is an iterator.

-tkc







More information about the Python-list mailing list