-1
from collections import deque 
Q = deque()

How to check if this deque is empty? Is there any function like isEmpty() to check this? Can someone help? I looked for a function in the documentation but unable to find any?

Ritika Gupta
  • 493
  • 4
  • 14

2 Answers2

1

Simply pythonic way:

from collections import deque 
Q = deque()
if not Q:
   print("Queue is empty")

You should know this power of great Python, that each collection becomes false if it is empty let it be sets, lists, dictionary, deque etc.

if data_structure:
    print('Data structure is not empty')
else:
   print('Data structure is empty')

Zain Arshad
  • 1,885
  • 1
  • 11
  • 26
0

The length of Q will be 0 if the input of deque() is empty:

from collections import deque
Q = deque()
assert len(Q) == 0
mangelfdz
  • 306
  • 2
  • 7
  • 1
    `__len__` simply invokes `len`, which is far more pythonic. `__len__` is a magic method. – A.J. Uppal Jun 05 '20 at 10:32
  • yes, you are right, that's easier – mangelfdz Jun 05 '20 at 10:36
  • @A.J.Uppal: You got it backwards; `len` is implemented in terms of `__len__`; that said, `len` is still the correct solution (it can access `__len__` through optimized C level interfaces, and it's just generally considered more Pythonic to use the special methods implicitly, not explicitly). – ShadowRanger Jun 07 '20 at 13:36