0

I need to get chunks of 5 elements from a Python list that contains several items. Process these 5 elements. Then get the next 5 elements, process then and then get the next 5 and so on till the end of list.

mylist = ['tt','aa','bb','xx','zz','qq','gg','hh','oo','ss','yy','ll','tt','kk'] #14 elements
#some loop here:
   chunk[0] = ['tt','aa','bb','xx','zz'] # after 1st iteration
   chunk[1] = ['qq','gg','hh','oo','ss'] # after 2nd iteration
   chunk[2] = ['yy','ll','tt','kk'] # after 3rd iteration

What would be a good way of writing this loop in Python (or maybe not even a loop!!!)?

I could do a non-Pythonic way by counting the number of elements in each iteration and then start from the last count in the next iteration but I am sure there is a good (efficient) way of doing this in Python.

pTeJa
  • 3
  • 1
  • 2

2 Answers2

1

Is this fine?

mylist = ['tt','aa','bb','xx','zz','qq','gg','hh','oo','ss','yy','ll','tt','kk']
chunk_size = 5

chunks = [mylist[i:i + chunk_size] for i in range(0, len(mylist), chunk_size)]

for chunk in chunks:
    print("Chunk:", chunk)
sifat
  • 353
  • 1
  • 8
0

you can use for loop starting with 0 and ending with length and each circle with 5. In each circle print a chunk from your list which starts with chunk value and ends with 5 + chunk value

mylist = ['tt','aa','bb','xx','zz','qq','gg','hh','oo','ss','yy','ll','tt','kk']

i = 1
for chunk in range(0, len(mylist), 5):
    print('chunk[',i,'] =', mylist[chunk: 5 + chunk])
    i += 1

If you require further clarification, please do not hesitate to ask me.