List Partition Comprehension (Feature Suggestion)

Yakov Shalunov yakov.shalunov at gmail.com
Tue Sep 22 15:34:14 EDT 2020


A possible alternative would be a partition library function in the same vein as `map` and `filter`
```
def partition(n, key, iter):
    """
    Partitions a list.
    Args: (n: the number of partitions), (key: function which takes elements and returns the index of the partition to place them in), (iter: the iterable to be partitioned)
    Returns: A tuple of lists partitioned per the key function. If this were a library function, this would likely return a tuple of generators instead in the same vein as `map` and `filter`.
    """
    lists = tuple([] for _ in range(n))
    for x in iter:
        lists[key(x)].append(x)
    return lists
```
Except it would be optimized like a library function (which means written in C, I believe)

On Tuesday, September 22, 2020 at 12:16:39 PM UTC-7, Yakov Shalunov wrote:
> 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