1

I have a loop like this:

def handle(self, *args, **options):
    database.objects.all().delete()
    for x in list:
        db.objects.create(
            ...add some data to database table...)

The list consists of 100 values. But I may run the loop with only 30 values at a time. And it's needed to have run all 100 values for the end of the script.

Why I have such a weird question, is that the script takes data from a third-party database, but it is allowed to take 30 objects at a time. So what I need is the script to take 30 values. Somehow pause and take the next 30 values and on the last time, take the 10 values, that are left and finishes.

Is something like this possible, or do I need to make my list into many small lists and run them one at a time?

3 Answers 3

1

Try this

a=0
for x in list:
    #whatever you are doing
    a+=1
    if a==30:
        break
#Then do it again
for x in list[a:]:
    #whatever you are doing
    a+=1
    if a==60:
        break
#Again
for x in list[a:]:
    #whatever you are doing
    a+=1
    if a==90:
        break

#Last Time!
for x in list[a:]:
    #whatever you are doing
Sign up to request clarification or add additional context in comments.

Comments

1

I suggest you slice the list in intervals of thirty elements, and call the function on each of these intervals.

Comments

0

This is easy using slicing. [:30] refers to a sublist from the beginning to the 30th element. [30:] refers to a sublist from after the 30th element to the end.

To handle lists in 30 value chunks, you can do this:

while len(list) > 0:
    dostuff(list[:30])
    list = list[30:]

To do stuff after every 30 elements, you could do:

while len(list) > 0:
    for item in list[:30]:
         doSomething(item) 

    dostuff()
    list = list[30:]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.