List Partition Comprehension (Feature Suggestion)

Greg Ewing greg.ewing at canterbury.ac.nz
Tue Sep 22 21:31:51 EDT 2020


On 23/09/20 7:16 am, Yakov Shalunov wrote:
> l0, l1 = ([x for x in l if cond(x) else x])
> l0, l1, l2 = ([x for x in l if cond0(x) else x**2 if cond1(x) else x**3])

This syntax seems a bit convoluted. One of the result expressions
is at the beginning as usual, but the rest are tacked on the end.
And it's far from obvious that it returns multiple lists instead
of a single list with alternative values, as you would get from

[(x if cond0(x) else x**2 if cond1(x) else x**3) for x in l]

which at first glance seems very similar.

Also I'm not sure how this would interact with the existing
comprehension syntax in its full generality, where you can
have multiple "for" and "if" clauses mixed in any order.

> A possible alternative would be a partition library function in the
> same vein as `map` and `filter`
That sounds like a much better idea for something that is so
rarely needed. Although it probably wouldn't be as fast as an
LC could potentially be, due to the need to call a user-supplied
function for every item.

-- 
Greg


More information about the Python-list mailing list