11

I'm working with Django and I have a queryset of objects that has been converted to a list (unpaid_sales). I'm executing a process that iterates through this list and operates on each item until either the list is empty, or a given integer (bucket) reaches zero.

This is how I set it up:

while unpaid_sales:
    while bucket > 0:
        unpaid_sale = unpaid_sales.pop(0)
        ...do stuff

In some cases, I am getting the following error:

pop from empty list

What's wrong with my logic?

3
  • 2
    Use a single while with or. Commented Oct 8, 2016 at 16:23
  • When does bucket change? Commented Oct 8, 2016 at 16:25
  • I understand now, thank you! Commented Oct 8, 2016 at 16:26

3 Answers 3

10

Your end criteria must be formulated a little differently: run the loop while there are items and the bucket is positive. or is not the right operation here.

while unpaid_sales and bucket > 0:
    unpaid_sale = unpaid_sales.pop(0)
    #do stuff
Sign up to request clarification or add additional context in comments.

3 Comments

They each have their own else conditions. Does elif work with while loops?
Not realy. But in this case you should probably use a normal if statement after the while loop
Got it. Thanks a lot!
7

Do not use separate whileloops. Do as follows :

while unpaid_sales and bucket > 0 :
    unpaid_sale = unpaid_sales.pop(0)
    ...do stuff

Comments

4

You should do a single loop: while bucket>0 and unpaid_sales. Here, you are popping elements in the bucket loop, and then just just check that bucket is positive, but you do not check that element_sales still has elements in it.

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.