I would like to break up a list into sublists of 3 elements each. I have this code, but it will give an index error when the length of the list is not divisible by 3.
mylist = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
# groups of n
n = 3
newlist = []
for ix in range(n, len(mylist) + n, n):
sublist = [mylist[ix-3], mylist[ix-2], mylist[ix-1]]
#print(ix, sublist)
newlist.append(sublist)
print(newlist)
''' output -->
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]]
'''
Is there a better way to do this?
I seem to have a mental block!