2

I'm looking to run an operation on all values of a list but 10 at a time. The problem is that on the final cycle of the for loop there are less than 10 values in the list. My current solution to this is to do the following:

for i in range(len(my_list) // 10):

    for i in range(10):

        # do operation

for i in range(len(my_list) % 10):

    # do operation

Or another solution would be:

while True:

    for i in range(10):

        if not my_list:

            break


        # do operation

    if not my_list:

        break

My question is if there's a better (and probably quite obvious) solution to this. I wasn't sure how to describe the issue, so there may be another question that already answers this if I had known the right terminology to look with. Sorry if this is the case.

John Muir
  • 55
  • 1
  • 3

2 Answers2

2

more_itertools.chunked will do the trick:

for chunk in more_itertools.chunked(my_list, 10):
    for item in chunk:  # 10 items or less
        # do operation
sanyassh
  • 8,100
  • 13
  • 36
  • 70
2

Given it’s a list, rather than an arbitrary iterable, you could just:

for start in range(0, len(my_list), 10): 
    # now my_list[start:start + 10] is the batch you want
    for x in my_list[start:start + 10]:
        do_something(x)
donkopotamus
  • 22,114
  • 2
  • 48
  • 60