Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - While-Loop until list is empty

Tags:

python

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?

like image 948
Adam Starrh Avatar asked Oct 08 '16 16:10

Adam Starrh


3 Answers

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
like image 185
tynn Avatar answered Oct 22 '22 08:10

tynn


Do not use separate whileloops. Do as follows :

while unpaid_sales and bucket > 0 :
    unpaid_sale = unpaid_sales.pop(0)
    ...do stuff
like image 26
MMF Avatar answered Oct 22 '22 08:10

MMF


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.

like image 4
Efferalgan Avatar answered Oct 22 '22 08:10

Efferalgan