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:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

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

{{ parent.tldr }}

{{ parent.urlSource.name }}