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!
>Solution :
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.