How to Print Deque in Python

Deque, pronounced as ‘deck’, stands for Double Ended Queue. It is a generalized version of Queue and Stack data structures that allows the insertion and removal of elements from either end.

In Python, the deque is a part of the collections module. This tutorial will guide you on how to print a deque in Python.

Step 1: Importing the deque

In Python, to use deque, first, you need to import it from the collections module. Here is how you can do that.

Step 2: Creating a Deque

Once imported, you can create a deque. You pass a list to the deque() function to convert it into a deque.

Step 3: Printing a Deque

To print a deque, use the print() function. A deque object prints just like a list.

In the case above, the output of the code would be:

deque(['a', 'b', 'c', 'd'])

Step 4: Looping over a Deque

You can also use a for loop to print the elements of the deque one by one. Here is an example.

The output of this code would be:

'a'
'b'
'c'
'd'

Display the Full Code

Here is the final version of the code.

Conclusion

Deque is an extremely useful data structure that combines the characteristics of both stacks and queues. Moreover, deque provides an excellent way to handle data efficiently.

The capability to utilize it from any end makes it perfect for certain types of data-handling operations. It is fast, easy, and convenient to use. You can apply deque for various real-world tasks such as keeping track of the last few events, storing history, etc.