3

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.

3 Answers 3

6

You can check in exactly the same way as you already do in the while loop:

while my_deque:
    alpha = my_deque.popleft()
    beta = my_deque.popleft() if my_deque else None
    gamma = my_deque.popleft() if my_deque else None

However, if alpha, beta and gamma constitute one unit of work, it might be a better idea to combine them into a tuple, and enqueue that.

2
  • When I execute my code block with an if statement in place of the while statement, it still does not work. Same error. From traceback: "Traceback (most recent call last): File "test.py", line 9, in <module> gamma = my_deque.popleft() IndexError: pop from an empty deque"
    – ccdpowell
    Mar 1, 2013 at 8:16
  • 1
    @ccdpowell: That's not what I meant. You need to check the queue for emptiness before every popleft(). I've updated the code to hopefully make it clearer.
    – NPE
    Mar 1, 2013 at 8:18
5

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?

2
  • This works. gamma is actually a key in a dictionary. I thought the try / except made it so all or none of the code in the try had to execute. Didn't realize that whatever had been executed before the exception would still be done. Thanks!
    – ccdpowell
    Mar 1, 2013 at 8:19
  • 1
    @ccdpowell: be careful though, if there is a possibility that other parts of the code may also raise IndexError the try-except may also catch that. It may be better to put the try except inside the while loop, to only surround the parts where you have mydeque.popleft(), but it really depends on what you're trying to do.
    – Lie Ryan
    Mar 1, 2013 at 8:25
0

If you know if advance how many items you're going to be popping from the queue, you can condition the loop on there being at least that many ready:

while len(my_deque) >= 3:
    alpha = my_deque.popleft()
    beta = my_deque.popleft()
    gamma = my_deque.popleft()

    # do stuff with alpha/beta/gamma here

If you don't know how many items may be requested, you can take an "easier to ask for forgiveness than permission" approach and loop unconditionally:

while True:
    try:
        alpha = my_deque.popleft()
        if alpha > 0:
            beta = my_deque.popleft()
            gamma = my_deque.popleft()
        else:
            beta = 0
            gamma = 0
    except IndexError:
        break

    # do stuff with alpha/beta/gamma here

If the pops happen in widely separated parts of the loop's code, you could use separate try/except blocks for each of them, rather than wrapping the whole thing in a single one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.