Adam Starrh Adam Starrh - 1 year ago 169
Python Question

Python - While-Loop until list is empty

I'm working with Django and I have a queryset of objects that has been converted to a list (

). 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 (
) reaches zero.

This is how I set it up:

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

In some cases, I am getting the following error:

pop from empty list

What's wrong with my logic?

Answer Source

Your end criteria must be formulated a little differently: 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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download