3

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]
falsetru
  • 357,413
  • 63
  • 732
  • 636
user3378649
  • 5,154
  • 14
  • 52
  • 76

1 Answers1

3

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]]
falsetru
  • 357,413
  • 63
  • 732
  • 636