0

Actually I am having list of 500 elements such as

list = [1,2,3,4,5...500]

Now I want to create a batch of of 32 elements and store in nested list where the main list contains nested list of 32-32 elements and last nested list contains 20 elements such as:

final_list = [[1,2,3,..,32],[33,34,35,..,64],..,[480,481,482,..500]]

I was trying with append from loop but not having exact idea how to do so.

final_list = []
for itr in range(0,500,32):
    final_list.append(l[0:itr])

Tried with various method but not able to find the correct logic. Any help would be great and thanks a lot in advance!!

2 Answers2

0

You can do this using a list comprehension:

final_list = [my_list[x:x+32] for x in range(0, len(my_list), 32)]

For example,

my_list = list(range(0, 500))
batch_size = 32
final_list = [my_list[n:n+batch_size] for n in range(0, len(my_list), batch_size)]

and the final output would be

[
  [0, 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],
...
]
Giorgos Myrianthous
  • 36,235
  • 20
  • 134
  • 156
0

You need to change the starting index as you move along in the for loop:

final_list = []
offset = 32
for itr in range(0, len(l), offset):
    final_list.append(l[itr:itr+offset])
print(final_list)
Krishna Chaurasia
  • 8,924
  • 6
  • 22
  • 35