You can do what you want with a simple list comprehension.
>>> a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> [a[i:i+3] for i in range(0, len(a), 3)]
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
If you want the last sub-list to be padded you can do this before the list comprehension:
>>> padding = 0
>>> a += [padding]*(3-len(a)%3)
Combining these together into a single function:
def group(sequence, group_length, padding=None):
if padding is not None:
sequence += [padding]*(group_length-len(sequence)%group_length)
return [sequence[i:i+group_length] for i in range(0, len(sequence), group_length)]
Going the other way:
def flatten(sequence):
return [item for sublist in sequence for item in sublist]
>>> a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> flatten(a)
[1, 2, 3, 4, 5, 6, 7, 8, 9]