Prevent Errors with Python deque Empty Handling

Deque is a data structure in Python through which one can perform insertion and deletion from both ends. It is also referred to as a double-ended queue. It works similarly to a queue and a stack, providing many functions. Hence, it is of great use to programmers.

Initializing empty deque

You need to import the collections module to use functionalities related to the deque module. For initialization, you need to specify the length of the deque. You can use the maxlen keyword for the same.

collections.deque([], 10)
# or
collections.deque(maxlen=10)

Need to check whether the deque is empty

In case we remove an element from an empty deque, you may get this error:

IndexError: pop from an empty deque

Hence, it sort of makes it necessary to check whether an element exists in the doubly-ended queue, i.e., whether it is empty or not.

len() function

You can check whether the queue is empty using the length of the deque. It is calculated using the len() function. The deque module is part of collections, so it has to be imported.

from collections import deque
deque1 = deque()
if len(deque1) == 0:
    print("Empty")

bool() method

False implies deque is without any content. This is an example of explicit conversion. The output will be True in case data exists.

# import deque using collections module
from collections import deque
deque1 = deque()
if bool(deque1) == False:
	print("Empty")

deque() with values

If you want to check whether the deque is empty from scratch, first import the deque from the collections module. Infinite looping can be used so that the loop breaks once the deque is data-free. So, the way deque is performed commonly, you can pop the elements one by one till you obtain an empty deque. Hence, your job’s done.

from collections import deque
deque1 = deque(["Geeks","for","Geeks"])
while(True):
	if deque1:
		print(deque1) 
        #means element exists in deque so we need to pop it.
		deque1.pop()
	else:
		print("Deque is empty")
		break

Empty bounded deque

You can check for the presence of elements in bounded deque too. The difference is that the length of the deque is specified beforehand. You will get a boolean output- True or False indicating whether the element is present in the deque.

q1 = deque(maxlen=4)
print(not q1)
#True will be the result.
#True means deque is empty

popleft() for deque

If you want to delete elements from the deque from the left, you can pop the left () function. The pop() function normally deletes from the right side. Hence, depending on the need, you can use these functions to empty the deque.

while deque1:
    pop_ans = deque1.popleft()
# will pop elements from left side only

As an alternative, one may use this approach too. It will fetch the same output.

while 0 < len(deque1):
    pop_ans = deque1.popleft()

clear() deque

It will make the deque empty. In other words, it removes all elements from the deque. Its syntax is:

Deque.clear()

Working of clear() deque

Assume that we have created a deque with elements. Now this function of the deque module will make the deque empty. It means that the length of the deque will be empty. So the given an example will demonstrate the same:

import collections
No= (1,2,3)
eDeque = collections.deque(No)
print("Deque elements are :")
print(eDeque)
print("Deque length:%d"%(len(eDeque)))
# remove all the elements of deque
eDeque.clear()
print("Deque post removing elements:")
print(eDeque)

Popping an empty deque

To pop an empty deque, you will get an index error. So it is better to use a try-except block to handle the exception. So, ordinarily, ele stores the popped element, and if the deque becomes empty, you will not get an index error, but the exception is handled.

try:
    while mydeque:
        ele = mydeque.popleft()
except IndexError:
    # empty mydeque

The time complexity of checking if the deque is empty

Consider this easy block of code. Performing a deque operation takes O(1) time, i.e., it is of order 1. It is constant; hence the given complexity is obtained. Even for other operations like searching in the deque, it is O(1).

from collections import deque
q = deque()
# iterate until deque is empty
while len(q):
   #perform deque action

How a deque differs from a queue?

The primary difference between a queue and a deque is that in a queue, elements are added from the ending while deletion is done from the beginning of the queue. A deque supports these operations from both ends.

Besides this, a queue supports LIFO, but deque has both FIFO and LIFO functions. Also, arrays and linked lists can help implement a queue, whereas a doubly linked list can be used in a doubly linked queue in a doubly linked queue.

What happens when you try to add an element in an already filled deque?

It gives an IllegalStateException. It can’t accept elements anymore as it is already full. So this implies that the deque is already full.

FAQs

What is the use of the clear() function with a deque?

It removes all elements from the deque. Zero parts will be left in the deque after this function call.

What are the different types of deques?

It can be either input or output restricted.

Conclusion

This article explained the different ways in which a deque can be emptied. You can check whether it is empty using a range of functions like the len() method, casting with bool() function, etc.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments