I bet I already wrote that sometime earlier, but I found myself today writing the following function:
def blocks(seq, block_len): """blocks(range(5),2) -> [[0, 1], [2, 3], ]""" seq_len = len(seq) if seq_len%block_len == 0: num_blocks = seq_len/block_len else: num_blocks = 1 + (seq_len/block_len) result = [ for i in xrange(num_blocks)] for idx, obj in enumerate(seq): result[idx/block_len].append(obj) return result
I am not satisfied with this implementation.
The challenge is to write it in a more elegant and short manner. Functions from Python’s standard modules are considered valid solutions.