Python - Iterating through a deque with popleft()

Viewed 3431

I've been looking for the best way to iterate through a deque while using popleft to use the first element and reduce the queue for each iteration. I essentially want to popleft the first in the deque, run some code using this value and then do the same process until there are no more values left in the deque.

The best I've found online is using a try and catch block to capture an IndexError:

try: 
    while mydeque: 
        value = mydeque.popleft()
except IndexError: 
# handle empty mydeque

Surely throwing an exception isn't the best way to do this. I'd be catching any IndexError occurring in the while loop as well, which isn't ideal. Using a for loop doesn't work as I'd be modifying the deque during the iteration.

What's the best way to do this?

3 Answers

When mydeque is empty, it resolves as False in the while loop.

while mydeque:
    value = mydeque.popleft()

This will run through all values in mydeque.

You can either use while mydeque:... as @slightlynybbled suggested or while 0 < len(mydeque):... what is basically the same.

while 0 < len(mydeque):
    value = mydeque.popleft()

You can put the try/except within the while loop; that way you can make sure it only catches the IndexError thrown by popleft

https://pymotw.com/2/collections/deque.html

while True:
  try:
    print d.popleft()
  except IndexError:
    break
Related