Queue in Python
Introduction
Similar to a stack, a queue is a linear data structure that uses FIFO (First In, First Out) ordering to store items. A queue removes the least recently added item first. Any line of customers waiting to access a sale where the customer who arrived first can access first is a good example of a queue.
Operations on Deque
- Enqueue: Adds an element to the queue. Overflow conditions are described as the queue being full. Time Complexity: O (1)
- Dequeue: Remove an element from the queue. In the same order that they are pushed, the items are popped. It's called an underflow condition if the queue is empty. Time Complexity: O (1)
- Front: Get the first item in the queue; Time Complexity: O (1)
- Rear: Obtain the last item in the queue. Time Complexity: O (1)
Implementation
A queue can be implemented in Python in a number of different ways. This blog describes how to implement a queue using Python library modules and data structures.
The following methods can be used to implement queue in Python:
- list
- collections.deque
- queue.Queue
Examples
Now we know what is Queue in Python, so lets see how to implement it using different approaches:
Example 1
Implementation using list
List is a data structure that comes with Python and can be used as a queue. Append() and pop() functions are used in place of the enqueue() and dequeue() functions. Lists, however, take a long time to perform this operation because adding or removing an element from the beginning requires shifting every other element by one, which takes O(n) time.
# Initializing a queue |
Output:
Starting queue |
Example 2
Implementation using collections.deque
Deque or Doubly Ended Queue in Python is implemented using “collections” module. By using Deque, we can do push and pop operations in O(1) time complexity from both the ends of the collection. So, in some cases Deque is preferred over the list as they are faster as compared to the list.
# Initializing a deque |
Output:
Starting deque |
Example 3
Implementation using queue.Queue
Python's built-in module Queue is used to implement queues. queue. Queue(maxsize) sets a variable's initial value to maxsize, its maximum size. An infinite queue is indicated by a maxsize of zero "0." The FIFO rule is used in this queue.
from queue import Queue |
Output:
0 |