0

I'm trying to operate on every 5 items in a list, but can't figure out how to handle the remaining items if they don't divide evenly into 5. Right now I'm using modulo, but I can't shake the feeling it's not quite the right answer. Here's an example...

list = ["ValA","ValB","ValC","ValD","ValE","ValF","ValG","ValH","ValI","ValJ","ValK","ValL","ValM","ValN",]
newlist = []
i = 0
for o in list:
  i += 1
  newlist.append(o)
  
  if i % 5 == 0:
    for obj in newlist:
      function_for(obj)
      newlist.clear()

This code will execute function_for() twice, but not a third time to handle the remaining 4 values. If I add an 'else' statement it runs on every execution.

What's the correct way to handle a situation like this?

  • 1
    Probably my most visited SO answer: [How do you split a list into evenly sized chunks?](https://stackoverflow.com/a/312464/736937) (Won't VTC because I don't want to solo close it) – jedwards Mar 22 '22 at 02:58
  • @jedwards Are you Ned or did you mean to link to a different answer? – Kelly Bundy Mar 22 '22 at 03:40

2 Answers2

2

This way is pretty easy, if you don't mind modifying the list:

mylist = ["ValA","ValB","ValC","ValD","ValE","ValF","ValG","ValH","ValI","ValJ","ValK","ValL","ValM","ValN",]
while mylist:
     function_for( mylist[:5] )
     mylist = mylist[5:]
Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
0

You can also check if the index is equal to the length of the list. (Additionally, it is more idiomatic to use enumerate instead of a counter variable here.)

lst = ["ValA","ValB","ValC","ValD","ValE","ValF","ValG","ValH","ValI","ValJ","ValK","ValL","ValM","ValN",]
newlist = []

for i, o in enumerate(lst, 1):
  newlist.append(o)
  if i % 5 == 0 or i == len(lst):
    print(newlist)
    newlist.clear()
Unmitigated
  • 76,500
  • 11
  • 62
  • 80