Is there a built-in Python function such that with
vals=[1,2,3,4,5]
then foo(vals,2) gives
[[1,2],[3,4],[5]]
I am looking for the behaviour that Wolfram Language gives with
Partition[Range@5, UpTo@2]
{{1, 2}, {3, 4}, {5}}
Is there a built-in Python function such that with
vals=[1,2,3,4,5]
then foo(vals,2) gives
[[1,2],[3,4],[5]]
I am looking for the behaviour that Wolfram Language gives with
Partition[Range@5, UpTo@2]
{{1, 2}, {3, 4}, {5}}
This is built into neither the Python language itself nor its standard library, but might be what you are looking for functionality-wise:
Install the third-party-library more-itertools (not to be confused with the itertools module, which is part of the Python standard library), e.g. with
pipenv install 'more-itertools >= 2.4'
Then you can use the function sliced() it provides:
from more_itertools import sliced
vals = [1,2,3,4,5]
slices = list(sliced(vals, 2))
print(slices)
Result:
[[1, 2], [3, 4], [5]]
If the iterable isn't sliceable, you can use chunked() from the same library instead of sliced.
 
    
    Try this: 'n' is the subgroup size. 'l' is the list
def groups(l, n):
    for i in range(0, len(l), n):
        yield l[i:i + n]
