Over a million developers have joined DZone.

Split Array Or String Into Smaller Arrays

·
Splits an array or string into smaller arrays of the given size. Inspired on the ruby one ;).


import math
# v = value to split, l = size of each chunk
f = lambda v, l: [v[i*l:(i+1)*l] for i in range(int(math.ceil(len(v)/float(l))))]


Example


>>> f('000000111111222222333333444444567', 6)
['000000', '111111', '222222', '333333', '444444', '567']

>>> f(tuple('000000111111222222333333444444567'), 6)
[('0', '0', '0', '0', '0', '0'), ('1', '1', '1', '1', '1', '1'), ('2', '2', '2', '2', '2', '2'), ('3', '3', '3', '3', '3', '3'), ('4', '4', '4', '4', '4', '4'), ('5', '6', '7')]


Long live python :). Of course, a lisp/haskell implementation probably blows this snippet out.
Topics:

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}