Search code examples
pythonpython-3.xlistwolfram-mathematicapartition

How to ragged partition a list in Python?


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}}

Solution

  • 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.