Here's how I'd do it. Iteration, but in a list comprehension. Note the type gets mixed; this may or may not be desired.
def sublist(seq, length):
return [seq[i:i + length] for i in xrange(0, len(seq), length)]
Usage:
>>> sublist((1, 2, 3, 4, 5), 1)
[(1,), (2,), (3,), (4,), (5,)]
>>> sublist([1, 2, 3, 4, 5], 2)
[[1, 2], [3, 4], [5]]
>>> sublist('12345', 3)
['123', '45']
>>> sublist([1, 2, 3, 4, 5], 73)
[[1, 2, 3, 4, 5]]
>>> sublist((1, 2, 3, 4, 5), 0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in sublist
ValueError: xrange() arg 3 must not be zero
Of course, you can easily make it produce a tuple
too if you want - replace the list comprehension [...]
with tuple(...)
. You could also replace seq[i:i + length]
with tuple(seq[i:i + length])
or list(seq[i:i + length])
to make it return a fixed type.