Search code examples
pythondeque

is there a different ways to check deque empty in python


Are they the same thing????

while len(deque)>0:
    deque.popleft()

while deque:
   deque.popleft()

so basically these two condition loops can avoid poping from empty queue?


Solution

  • They're the same, but PEP 8 prefers the second version. I'm not convinced that it's always easier to read though, so use your own judgement.

    http://www.python.org/dev/peps/pep-0008/#programming-recommendations

    For sequences, (strings, lists, tuples), use the fact that empty sequences are false.

    Yes: if not seq:
         if seq:
    
    No: if len(seq)
        if not len(seq)