Split list into list of list with range n

Is there any pythonic path to Split list for list 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]

      

+3


source to share


1 answer


Using a 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]]

      

+3


source







All Articles