Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python while loop popleft() - ERROR: Empty deque

I am looking for a more elegant solution to this loop. My deques are created dynamically and can vary in length. In the example below the list is only two items long and could be up to 3 items long. In my application, the lists can be up to 30 items long. Therefore, I want to avoid writing a lot of if statements and have the code stop executing once the deque is empty.

from collections import deque

my_list = [ 1,2 ]
my_deque = deque ( my_list )

while my_deque:
    alpha = my_deque.popleft()
    beta = my_deque.popleft()
    gamma = my_deque.popleft()

The code above executes all three commands and on the gamma command returns an "IndexError: pop from an empty deque." I understand why this error is happening, but want to know if there is a trick I am missing to evaluate whether a list/deque is empty or not in the middle of a while loop (or another creative way to loop through a long list).

Thanks for the help.

like image 600
ccdpowell Avatar asked Oct 16 '25 05:10

ccdpowell


1 Answers

You can catch the IndexError:

try:
    while mydeque:
        alpha = mydeque.popleft()
        beta = mydeque.popleft()
        gamma = mydeque.popleft()
except IndexError:
    # handle empty mydeque

What are you trying to do? Why do you want to check that the mydeque is empty?

like image 115
Lie Ryan Avatar answered Oct 18 '25 17:10

Lie Ryan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!