Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Iterating through a deque with popleft() [duplicate]

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?

like image 882
dandev91 Avatar asked Oct 20 '25 14:10

dandev91


1 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.

like image 98
slightlynybbled Avatar answered Oct 23 '25 04:10

slightlynybbled



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!