List slice feature that allows to create sub-lists

>>> my_list = [0, 1, 2, 3, 4, 5]
>>> my_list[0:2::3]
[[0, 1], [2, 3], [4, 5]]

It would be nice to see that feature for the list.

I found a way to do it in Python :slight_smile: You can check out my implementation in here

>>> my_list = [0, 1, 2, 3, 4, 5]
>>> my_list[0:2::3]
[[0, 1], [2, 3], [4, 5]]

It would be nice to see that feature for the list.

Why? What’s your use case?

Not everything needs special syntactic support, or even direct support
in the stdlib.

Note that this would add an extra field/feature to the slice type,
which everyone would have to accomodate in the many places slices are
used, even if that accomodation is “raise an exception if the 4th field
is not None”. And it would make all slices slightly larger, a memory
cost applied to every programme on the planet.

I suppose this syntax might make a new slice4 (terrible name) which
subclasses slice? But then it still needs accomodating everywhere.

I found a way to do it in Python :slight_smile: You can check out my implementation in here

You could probably do something funky using itertools. I haven’t tried.

You could publish your sublist implementation as a package on PyPI for
people to find and use. See if it gets traction.

Cheers,
Cameron Simpson cs@cskk.id.au

In Python 3.12, we will have itertools.batched():

>>> from itertools import batched
>>> list(batched([0, 1, 2, 3, 4, 5], 2))
[[0, 1], [2, 3], [4, 5]]

https://docs.python.org/3.12/library/itertools.html#itertools.batched

7 Likes

It’s look pretty good, just as I thought. Now my suggestion seems useless :slight_smile:

#coding: sublist
primes = [2, 3, 5, 7, 11, 13, 17, 19]
first_pair, second_pair = primes[0:2::2]

print(f'Sum of first pair: {sum(first_pair)}')
print(f'Sum of second pair: {sum(second_pair)}')
Sum of first pair: 5
Sum of second pair: 12

Now that I can do this with itertools.batched(), the idea I suggested is no longer needed.

1 Like

This probably should be a separate post, but why does itertools.batched return an iterable of lists instead of an iterable of iterables? (Or even iterable of tuples like itertools.product?)

This was discussed at length in the dedicated thread for adding itertools.batched: Add batching function to itertools module

1 Like

An iterable of iterables was suggested during the discussions:

but they went with lists. I was fine with lists myself.

Regarding tuples, a list is easier to build, and a more flexible thing
to return in that it doesn’t constrain the caller’s use of each batch as
much.

Cheers,
Cameron Simpson cs@cskk.id.au