-2

My code now: random_lst = [1,2,3,4,5,6,7,8,9]

What's practical way in Python to make list of lists from list?

My goal: [[1,2,3],[4,5,6],[7,8,9]]

Juho M
  • 349
  • 2
  • 9
  • 19

1 Answers1

3

You can use this :

random_lst = [1,2,3,4,5,6,7,8,9]
new_lst = [random_lst[i:i+3] for i in range(0, len(random_lst), 3)]
print(new_lst) # => [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

For other numbers :

random_lst = [1,2,3,4,5,6,7,8,9]

def split_n(lst, n):
  return [lst[i:i+n] for i in range(0, len(lst), n)]

print(split_n(random_lst, 1)) # => [[1], [2], [3], [4], [5], [6], [7], [8], [9]]
print(split_n(random_lst, 2)) # => [[1, 2], [3, 4], [5, 6], [7, 8], [9]]
print(split_n(random_lst, 3)) # => [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(split_n(random_lst, 4)) # => [[1, 2, 3, 4], [5, 6, 7, 8], [9]]
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55