Is there any pythonic way to Split list to list of list with range 3.
x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
y = [[1,2,3], [4,5,6], [7,8,9]]
prev,re= [],[]
for a in x:
if len(prev)==3:
re+=prev
prev=[]
else:
prev+=[a]
Is there any pythonic way to Split list to list of list with range 3.
x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
y = [[1,2,3], [4,5,6], [7,8,9]]
prev,re= [],[]
for a in x:
if len(prev)==3:
re+=prev
prev=[]
else:
prev+=[a]
Using list comprehension:
>>> x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> n = 3
>>> [x[i:i+n] for i in range(0, len(x), n)]
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]