2

I want to split a list into sublists of specific length and store the remaining elements in other list.

For example:

Initial list is: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10,11]

I want to divide it into sublists or 3 numbers, and the remaining in a separate sublist.

I need result as : [[1,2,3],[4,5,6],[7,8,9],[10,11]]
I'mahdi
  • 23,382
  • 5
  • 22
  • 30

1 Answers1

3

You can use range(start, end, step).

lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10,11]
res = [lst[i:i+3] for i in range(0, len(lst), 3)]
print(res)

[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11]]
I'mahdi
  • 23,382
  • 5
  • 22
  • 30