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

Martti Kühne mar77i at mar77i.ch
Tue Oct 18 03:37:23 EDT 2016


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


Thinking about it, though, I ended up exactly where you are now,
except that I then thought about where an item would be known, and it
seemed to me, yes, an item would be more likely known *after* looping
over it rather than before:

[bi for bi in before for before in iterable] # why should "before"
exist before it is looped over?

correctly:
[bi for before in iterable for bi in before]

it doesn't, it should be declared to the right hand side and only the
result is kept over at the left hand edge.

On a same note, with if expressions the picture might look different:

[bi for bi in before for before in iterable if before[0] < 3] # ... is
bi filtered now or not?

correctly:
[bi for before in iterable if before[0] < 3 for bi in before]

it is filtered very clearly this way.

cheers!
mar77i


More information about the Python-ideas mailing list