![]() |
In Python, Queue and Deque are the data structures used for managing collections of elements in a first-in, first-out (FIFO) manner. In this article, we will learn to implement queues using collections.deque in Python. Create Queue Using Collections.deque In PythonBelow, is the Implementation of Creating Queue Using Collections.Deque in Python: Step 1: Importing collections.dequeIn the below step, we import the deque class from the collections module using the statement from the collections import deque. This allows us to access the functionality of the deque data structure.
Step 2: Defining the Queue ClassIn the below step, we define the Queue class with methods to manipulate a queue data structure. The __init__ method initializes an empty deque to store queue elements. The enqueue, dequeue, peek, is_empty, and size methods handle adding, removing, peeking at the front, checking emptiness, and getting the size of the queue, respectively, using the deque’s operations.
Step 3: Using the QueueIn the below step, we perform how to use the Queue class we defined. We create a queue instance named queue, enqueue elements 10, 20, and 30 into the queue, dequeue an element from the queue, peek at the front element, check if the queue is empty, and get its size.
Complete CodeBelow, is the complete code for creating a queue using collections.deque in Python. main.py
Output Dequeued item: 10 Front item: 20 Is queue empty? False Queue size: 2 |
Reffered: https://www.geeksforgeeks.org
Python |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |