List Partition Comprehension (Feature Suggestion)

Yakov Shalunov yakov.shalunov at gmail.com
Tue Sep 22 15:16:13 EDT 2020


Python list comprehension is substantially faster than plan iteration, to the point where
```
l0, l1 = [],[]
for x in l:
    if cond(x):
        l0.append(x)
    else:
        l1.append(x)
```
runs at about the same speed as
```
l0 = [x for x in l if cond(x)]
l1 = [x for x in l if not cond(x)]
```
assuming `cond` is a computationally light conditional.
While this isn't an extremely common use, I suggest a "partition comprehension" syntax which extends normal filtered-generator syntax. Such as:
```
l0, l1 = ([x for x in l if cond(x) else x])
```
(parenthesis there to indicate that the output is a tuple)
It could allow extension to n-way partitions as well. Because elif doesn't fit nicely in-line, it would probably be nicer to do it like:
```
l0, l1, l2 = ([x for x in l if cond0(x) else x**2 if cond1(x) else x**3])
```
So l0 would be all elements that match cond0, l1 would be squares of all that match cond1, and l2 would be cubes of everything that matches neither.


More information about the Python-list mailing list