pythonclojure

python equivalent to clojure's partition-all?


looking for something in python's standard lib or a syntax trick.

for non-clojure programmers, partition-all should have these semantics:

partition_all(16, lst) == [lst[0:16], lst[16:32], lst[32:48], lst[48:60]]

assuming len(lst) == 60


Solution

  • There is no such function in Python. You can do this:

    from itertools import islice
    def chunkwise(n, iterable):
        it = iter(iterable)
        while True:
            chunk = list(islice(it, n))
            if not chunk: 
                break
            yield chunk
    
    print list(chunkwise(3, range(10)))
    # [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]