To check if a deque variable is empty in Python, you can check if the deque has length 0.

from collections import deque

d = deque()

print(len(d) == 0)

#Output:
True

You can also convert it to a boolean and check if the deque converted to a boolean is False.

from collections import deque

d = deque()

print(bool(d) == False)

#Output:
True

The deque object from the collections module gives us a data structure which is a double-ended queue.

With deque in Python, we get fast and memory-efficient ways to prepend, append, and remove items from a collection of data.

When working with deque in Python, the ability to check if a deque is empty can be important. This can be valuable because if you try to use the popleft() function on an empty deque, then you will raise a IndexError.

To check if a deque variable is empty in Python, you can check if the deque has length 0.

Below shows a simple example of how you can check if a deque object is empty with the len() function.

from collections import deque

d = deque()

print(len(d) == 0)

#Output:
True

You can also convert it to a boolean and check if the deque converted to a boolean is False.

Below shows a simple example of how you can check if a deque object is empty with the bool() function.

from collections import deque

d = deque()

print(bool(d) == False)

#Output:
True

Hopefully this article has been useful for you to learn how to check if a deque object is empty in Python

Categorized in:

Python,

Last Update: February 26, 2024