[Python-ideas] Fwd: Fwd: Fwd: unpacking generalisations for list comprehension

Random832 random832 at fastmail.com
Mon Oct 17 22:50:55 EDT 2016


On Mon, Oct 17, 2016, at 22:17, David Mertz wrote:
> > [*range(x) for x in range(4)]
>
> As Paul or someone pointed out, that's a fairly odd thing to do.

I agree with the specific example of it being an odd thing to do with
range, it was just an attempt to illustrate with a concrete example.

>  It's the first time that use case has been mentioned in this thread.

I think that in general the "body involves a subexpression returning an
iterable other than the bare loop variable" has been covered before,
though it might not have been clear at all times that that was what was
being discussed.

Frankly, I think it's rare that something of the form "x for x ..." is
best written with a comprehension in the first place, and the same would
be true for "*x for x..." so I didn't like that some of the translations
being discussed only work well for that case.

> Of course, it's *really simple* to spell that in a natural way with
> existing syntax that isn't confusing like yours:
> 
>     [x for end in range(4) for x in range(end)]

I feel like I should be honest about something else - I'm always a
little bit confused by the ordering for comprehensions involving
multiple clauses. For me, it's the fact that:
[[a for a in b] for b in ['uvw', 'xyz']] == [['u', 'v', 'w'], ['x', 'y',
'z']]
which makes me want to write:
[a for a in b for b in ['uvw', 'xyz']]
but that's an error, and it actually needs to be
[a for b in ['uvw', 'xyz'] for a in b] == ['u', 'v', 'w', 'x', 'y', 'z']

So when this talk of readability issues comes up and the recommended
alternative is something that I don't really find readable, it's
frustrating. To me this proposal is something that would allow for more
things to be expressed without resorting to multi-loop comprehensions.

> There is no possible way to construct something that would use the
> proposed syntax that can't be expressed more naturally with a nested
> loop... because it's just confusing syntax sugar for exactly that.
> 
> Your example looks like some sort of interview quiz question to see if
> someone knows obscure and unusual syntax.


More information about the Python-ideas mailing list