-1

Let's say I want to make a list of lists:

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

How do I make a loop that immediately creates a new list (ex: [4,5,6]) AFTER the previous list is filled with 3 elements?

Right now, all I can do is:

[ [1, 2, 3, 4, 5, 6.... ] ], essentially a giant list within a list, instead of this giant list being split into lists with 3 elements each.

Mazdak
  • 105,000
  • 18
  • 159
  • 188
Python noob
  • 173
  • 1
  • 1
  • 6

2 Answers2

2

Use range within a list comprehension :

>>> [range(i,i+3) for i in range(1,10,3)]
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Mazdak
  • 105,000
  • 18
  • 159
  • 188
0
a=range(100)

List_of_lists=[a[i:i+3] for i in range(1, 100, 3)]

print List_of_lists

[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15], [16, 17, 18], [19, 20, 21], [22, 23, 24], [25, 26, 27], [28, 29, 30], [31, 32, 33], [34, 35, 
36], [37, 38, 39], [40, 41, 42], [43, 44, 45], [46, 47, 48], [49, 50, 51], [52, 53, 54], [55, 56, 57], [58, 59, 60], [61, 62, 63], [64, 65, 66], [67, 68, 6
9], [70, 71, 72], [73, 74, 75], [76, 77, 78], [79, 80, 81], [82, 83, 84], [85, 86, 87], [88, 89, 90], [91, 92, 93], [94, 95, 96], [97, 98, 99]]    
Konstantin
  • 24,271
  • 5
  • 48
  • 65
Tirupati Rao
  • 615
  • 6
  • 24