Home > Mobile >  How to handle operating on items in a list without perfectly even len()?
How to handle operating on items in a list without perfectly even len()?

Time:03-22

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?

CodePudding user response:

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:]

CodePudding user response:

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()
  • Related