How to Check if a Deque Is Empty in Python
The deque (double-ended queue) from Python's collections module is a versatile data structure that supports efficient insertion and deletion from both ends. It's commonly used as both a queue and a stack. However, attempting to remove an element from an empty deque raises an IndexError, which can crash your program unexpectedly.
In this guide, you'll learn several reliable ways to check if a deque is empty in Python before performing operations on it, keeping your code robust and error-free.
Why You Should Check Before Popping
Before diving into the solutions, let's see what happens when you try to remove an element from an empty deque:
from collections import deque
empty_deque = deque()
empty_deque.pop()
Output:
Traceback (most recent call last):
File "main.py", line 4, in <module>
empty_deque.pop()
IndexError: pop from an empty deque
This IndexError will terminate your program if not handled. Checking whether the deque is empty before calling pop() or popleft() prevents this issue entirely.
Using Truthiness (The Pythonic Way)
The most Pythonic and recommended approach is to use the deque directly in a boolean context. An empty deque evaluates to False, while a non-empty deque evaluates to True.
from collections import deque
my_deque = deque()
if not my_deque:
print("Deque is empty.")
else:
print(f"Deque has {len(my_deque)} elements.")
Output:
Deque is empty.
This works because Python's built-in collections, including list, dict, set, and deque, are falsy when empty and truthy when they contain elements.
from collections import deque
# Non-empty deque
my_deque = deque([1, 2, 3])
if not my_deque:
print("Deque is empty.")
else:
print(f"Deque has {len(my_deque)} elements.")
Output:
Deque has 3 elements.
Using if not my_deque is the idiomatic Python style recommended by PEP 8. It's clean, readable, and efficient.
Using len()
You can also check if the deque is empty by comparing its length to zero using the len() function.
from collections import deque
my_deque = deque()
if len(my_deque) == 0:
print("Deque is empty.")
else:
print("Deque is not empty.")
Output:
Deque is empty.
While this works perfectly, if len(my_deque) == 0 is more verbose than if not my_deque. Both have O(1) time complexity since len() on a deque is a constant-time operation. However, the truthiness check is generally preferred for its simplicity.
Using bool()
You can explicitly convert the deque to a boolean using the bool() function. An empty deque returns False, and a non-empty one returns True.
from collections import deque
my_deque = deque()
if bool(my_deque) == False:
print("Deque is empty.")
else:
print("Deque is not empty.")
Output:
Deque is empty.
While bool(my_deque) == False works, comparing against False directly is considered non-Pythonic. Instead, simply use the truthiness check:
from collections import deque
my_deque = deque()
# ❌ Avoid this
if bool(my_deque) == False:
print("Empty")
# ✅ Prefer this
if not my_deque:
print("Empty")
Both produce the same result, but the second form is cleaner and follows Python best practices.
Practical Example: Safely Draining a Deque
A common real-world scenario is processing all elements in a deque until it's empty. Here's how to do it safely:
from collections import deque
my_deque = deque(["task_1", "task_2", "task_3"])
while my_deque:
current = my_deque.popleft()
print(f"Processing: {current} | Remaining: {list(my_deque)}")
print("All tasks processed. Deque is empty.")
Output:
Processing: task_1 | Remaining: ['task_2', 'task_3']
Processing: task_2 | Remaining: ['task_3']
Processing: task_3 | Remaining: []
All tasks processed. Deque is empty.
The while my_deque loop continues as long as the deque has elements. Once the deque is empty, the condition becomes False and the loop exits naturally, so no IndexError possible.
Using Try-Except as an Alternative
In some cases, especially when the deque is rarely empty, it can be more efficient to use a try-except block instead of checking first. This follows the Python philosophy of EAFP (Easier to Ask Forgiveness than Permission):
from collections import deque
my_deque = deque()
try:
item = my_deque.pop()
print(f"Popped: {item}")
except IndexError:
print("Cannot pop: deque is empty.")
Output:
Cannot pop: deque is empty.
- Use
if not my_dequewhen the deque is frequently empty. It avoids the overhead of exception handling. - Use
try/exceptwhen the deque is almost always non-empty. Catching a rare exception is cheaper than checking every time.
Quick Comparison of Methods
| Method | Syntax | Pythonic | Time Complexity |
|---|---|---|---|
| Truthiness check | if not my_deque: | ✅ Best | O(1) |
len() comparison | if len(my_deque) == 0: | ✅ Good | O(1) |
bool() conversion | if bool(my_deque) == False: | ❌ Verbose | O(1) |
| Try-except | try: my_deque.pop() | ✅ Good (EAFP) | O(1) |
Conclusion
Checking if a deque is empty before performing operations on it is essential to avoid IndexError exceptions. Python offers several ways to do this:
if not my_dequeis the most Pythonic and recommended approach. It's concise, readable, and efficient.len(my_deque) == 0is explicit and clear, making it a solid alternative when readability is a priority.try/except IndexErrorfollows the EAFP pattern and works best when empty deques are rare edge cases.
For most situations, simply using if not my_deque before calling pop() or popleft() is the cleanest and most effective solution.