Home > Blockchain >  Python - limit iteration per loop, but go through the whole loop in next iterations
Python - limit iteration per loop, but go through the whole loop in next iterations

Time:09-29

I need to limit number of elements that will be executed through one loop iteration, but after that, I need to continue from the point where loop stopped, and re-run the loop, until all the elements are processed through multiple loop iterations..

Let's say I have a list:

list1=[1,2,3,4,5,6,7,8,9,10]

and static limiter:

limit = 4

so in this case I want to add only 4 elements from the list (1,2,3,4) into some other list and do some kind of processing and parsing, and after that I want to add next 4 elements (5,6,7,8), and do the processing, and at the end the rest of the elements (9,10).

My current code only process the first 4 elements. I used islice for this.

from itertools import islice

list1=[1,2,3,4,5,6,7,8,9,10]
new_list=[]
limit = 4
for item in islice(list1, limit):
    new_list.append(item)
print (new_list)

So, the desired output is to have new_list printed first only with elements [1,2,3,4], after that list is being reset and populated with elements [5,6,7,8] and at the end list is reset with elements [9,10]. Solution should not involve dealing with additional new_lists - only one new list object.

Number of elements in list1 can be less than a limit value.

Note: I am using python2.7 (can't use python 3 on the customer server).

Thanks a lot!

CodePudding user response:

Something like this should work:

list1 = [1,2,3,4,5,6,7,8,9,10]
new_list = []
limit = 4
for item in list1:
    new_list.append(item)
    if len(new_list) == limit:
        print(new_list)
        new_list = []
print(new_list)

Essentially, the loop will add entries to new_list, and when there are limit entries in new_list, new_list is emptied.

CodePudding user response:

This may help: This code initially makes a deep copy of your original list, then the while loop process the list in steps delimited for the number defined in the limit. So in this case it will take 4 elements "do something" (in this case is just poping the elements from the list). When the range is less than the limit it will just take the last elements.

import copy

list1=[1,2,3,4,5,6,7,8,9,10]
list2 = copy.deepcopy(list1)

new_list=[]
limit = 4
counter = 0

while list2:
    try:
        for i in range(0, limit):
            removed_element = list2.pop()
            new_list.append(removed_element)
        print("cicle finished")
    except:
        for i in list2:
            removed_element = list2.pop()
            new_list.append(removed_element)
        print("last cicle")
  • Related