Queue is a linear data structure that stores items in a First-In/First Out(FIFO) manner. In queue, the data element that is inserted first will be removed first.
Operations that can be performed on the queue are:
Enqueue
:
It adds an item to the queue. If the queue is full, then it is said to be an Overflow condition.
Dequeue
: It removes an item from the queue. The items are popped in the same order in which they are
pushed. If the queue is empty, then it is said to be an Underflow condition.
Front
: It gives the front item from the queue.
Rear
: It gives the last item from the queue.
Note: The time complexity for all of the above operations is O(1).
Queue in Python can be implemented in the following ways:
Queue
modulecollections.deque
moduleIn Python lists, we can use the append()
method to add elements to the end of the list, effectively simulating the enqueue operation and the pop()
method to remove elements from the beginning with an index of 0, effectively simulating the dequeue operation easily.
# implementing Queue using List :q=[]q.append(10)q.append(100)q.append(1000)q.append(10000)print("Initial Queue is:",q)print(q.pop(0))print(q.pop(0))print(q.pop(0))print("After Removing elements:",q)def is_empty():return len(q) == 0def size():return len(q)print("Check queue is empty or not", is_empty())print("Size of the queue:", size())
Queue
moduleThe Queue
module in Python provides a convenient and thread-safe way to implement a FIFO (First-In-First-Out) queue. The following methods we have used to implement queue:
put()
: It inserts the specified element into the queue.
get()
: It removes and returns the element at the front of the queue.
empty()
: It returns True
if the queue is empty; otherwise, it returns False
.
qsize()
: It returns the size of the queue.
# implment queue using queue modulefrom queue import Queueq=Queue(maxsize=4)print("Initial Size Before Insertion:",q.qsize())q.put('A')q.put('AA')q.put('AAA')q.put('AAAA')print("After Insertion:",q.qsize())print("Queue is Full or Not:",q.full())print("Size of Queue:",q.qsize())print("Removing Elements:")print(q.get())print(q.get())print(q.get())print("Empty or Not??",q.empty())print(q.get())print("Empty or Not??",q.empty())print("Size of Queue:",q.qsize())
collections.deque
moduleThe collections.deque
module in Python provides a double-ended queue (deque) that allows adding and removing elements efficiently from both ends. The following methods we have used to implement queue:
append()
: It inserts the specified element into the queue.
popleft()
: It removes and returns the element at the front of the queue.
from collections import dequeq=deque()q.append(10)q.append(100)q.append(1000)q.append(10000)print("Initial Queue is:",q)print(q.popleft())print(q.popleft())print("After Removing elements:",q)