×

Queue in Python

Queue Python Ds F

In python, the queue is an abstract data structure that stores elements linearly. The items in a queue follow the First-In/First-Out (FIFO) order. This means that the first element to be inserted in a queue will be the first one to be removed.

We can illustrate the “queue” data structure with the real-life example of a queue of people at a bank. A person will enter the queue at the last position. The first person to enter the queue will be the first to receive his services and leave. This demonstrates how the FIFO manner works. The person or the data item inserted first in the queue will be the first to be removed.

Image 110
Table of Contents

Queue Operations

Various operations can be performed on a queue in python.

  • Create Queue – The creation of a queue is the most fundamental operation. Just like any other linear data structure, a queue can be implemented in python and used to store data elements.
  • Enqueue – The enqueue operation is used to insert new elements into a queue. The new elements are entered at the end of the queue.
  • Dequeue The dequeue function is used for the removal of a data item from a queue data structure. Data items are also removed from the beginning of the queue following the FIFO approach.
  • Peek – Peek operation is used to retrieve the first element of the queue without deleting it.
  • isEmpty – The isEmpty method returns whether a queue is empty or not, returns a boolean value of True if the queue is empty, otherwise it returns False.
  • isFull – The isFull method returns whether a queue is full or not, returns a boolean value of True if the queue is full, otherwise it returns False.
  • deleteQueue – Removes all the data elements and free up the allocated memory space.

Queue creation using List without size limit

The creation of Queue using the list data structure in python is a simple process. Firstly, we create a queue class and initialize an “int” list inside the “Queue” class. We also create the “__str__” function of this class to return the string version of our queue in the desired order. When we create “__str__” function, it modifies the “__str__” function of python.

The advantage of using the list data structure to create the Queue is that it is easy to implement and the list can be limitless. We can use the in-built functions, append and pop, associated with lists. However, its implementation may become slower as the size of the list increases.

#Creating Queue class using list without size limit
class Queue:
      def __init__(self):
        self.items = []

#Modifying the __str__ function to return the desired string version of Queue
      def __str__(self):
        values = [str(x) for x in self.items]
        return ' '.join(values)

Time and Space Complexity

The time complexity of creating a Queue using a list is O(1) as it takes a constant amount of time to initialize a list. The space complexity is O(1) as well since no additional memory is required.

Operations on Queue using List without size limit

isEmpty

The isEmpty function is used to check whether the given queue is empty or not. If there are no elements in the core list, we return a boolean value of True, otherwise False.

#isEmpty Function to check whether the queue is empty
def isEmpty(self):
     if self.list == []:
         return True
     else:
         return False

#Example
tempQueue = Queue()
print(tempQueue.isEmpty())

#Output
True

O(1) is the time complexity as it takes a constant time for initialization and space complexity is O(1) as no additional memory is required.

enqueue

The enqueue function is used to insert elements at the end of a given queue. We use the built-in function on the list data structure to implement the same.

#enqueue Function to insert elements 
def enqueue(self, value):
    self.items.append(value)
    return "The element is successfully inserted at the end of Queue."

#Example
tempQueue = Queue()
tempQueue.enqueue(1)
tempQueue.enqueue(2)
tempQueue.enqueue(3)
print(tempQueue)

#Output
1 2 3

dequeue

The dequeue function is used to delete elements from the beginning of a given queue. This function is implemented by using the in-built pop function of the list data structure.

#dequeue Function to remove elements
def dequeue(self):
     if self.isEmpty():
         return "The Queue does not exist."
     else:
         return self.items.pop(0)

#Example
tempQueue = Queue()
tempQueue.enqueue(1)
tempQueue.enqueue(2)
tempQueue.enqueue(3)
tempQueue.dequeue()
print(tempQueue)

#Output
2 3

peek

The peek function returns the topmost element of the queue without deleting it. This is accomplished by indexing the given list and returning the first element.

#peek Function to return the topmost element
def peek(self):
    if self.isEmpty():
         return "The is not any element in the Queue"
    else:
         return self.items[0]

#Example
tempQueue = Queue()
tempQueue.enqueue(1)
tempQueue.enqueue(2)
tempQueue.enqueue(3)
print(tempQueue.peek())
print(tempQueue)

#Output
1

delete

The delete function is used to remove the entire queue. To delete the entire queue, we set the list to None and free up all the allocated space.

#delete Function to the entire queue.
def delete(self):
    self.items = None

#Example
tempQueue = Queue()
tempQueue.enqueue(1)
tempQueue.enqueue(2)
tempQueue.enqueue(3)
tempQueue.delete()

Time and Space Complexity for Operations on Queue built using List

Time ComplexitySpaceComplexity
Create QueueO(1)O(1)
EnqueueO(n)O(1)
DequeueO(n)O(1)
PeekO(1)O(1)
isEmptyO(1)O(1)
Delete Entire QueueO(1)O(1)

Creation of Queue using Linked List

In python, we can implement a queue by using a linked list as its inclusive data structure. The complexity of the data structure increases but operations such as insertion, deletion, traversal, etc. take significantly less amount of time to execute.

To create a queue using the linked list data structure, firstly we create the node and linked list class for our fundamental data structure. Then we initialize the “Queue” class which includes an instance of the linked list data structure.

#Creating the Node class
class Node:
      def __init__(self, value=None):
         self.value = value
         self.next = None
    
      def __str__(self):
         return str(self.value)

#Create the Linked List class
class LinkedList:
      def __init__(self):
         self.head = None
         self.tail = None
    
      #Iterator function
      def __iter__(self):
         current_node = self.head
         while current_node:
             yield current_node
             current_node = current_node.next

#Creating Queue class using list linked list
class Queue:
    def __init__(self):
        self.LinkedList = LinkedList()

#Modifying the __str__ function to return the desired string version of Queue
    def __str__(self):
        values = [str(x) for x in self.LinkedList]
        return ' '.join(values)

isEmpty

If the head node of the linked list is none, this indicates that the queue is empty. We return a True boolean value if the head node does not exist, otherwise False.

#isEmpty Function to check whether the queue is empty
def isEmpty(self):
     if self.LinkedList.head == None:
         return True
     else:
         return False

#Example
tempQueue = Queue()
print(tempQueue.isEmpty())

#Output
True

enqueue

New elements are inserted at the end of the linked list in a queue. Every time we insert a data item into the queue, the tail node points to the newly added node.

#enqueue Function to insert elements 
def enqueue(self, value):
    new_node = Node(value)
    if self.LinkedList.head == None:
         self.LinkedList.head = new_node
         self.LinkedList.tail = new_node
    else:
         self.LinkedList.tail.next = new_node
         self.LinkedList.tail = new_node

#Example
tempQueue = Queue()
tempQueue.enqueue(1)
tempQueue.enqueue(2)
tempQueue.enqueue(3)
print(tempQueue)

#Output
1 2 3

dequeue

The elements are removed from the queue with the help of the head reference. The head node always points to the element at the top of the queue, which needs to be removed.

#dequeue Function to remove elements
def dequeue(self):
        if self.isEmpty():
            return "The Queue does not exist."
        else:
            temp_node = self.LinkedList.head
            if self.LinkedList.head == self.LinkedList.tail:
                self.LinkedList.head = None
                self.LinkedList.tail = None
            else:
                self.LinkedList.head = self.LinkedList.head.next
            return temp_node

#Example
tempQueue = Queue()
tempQueue.enqueue(1)
tempQueue.enqueue(2)
tempQueue.enqueue(3)
tempQueue.dequeue()
print(tempQueue)

#Output
2
1

peek

The peek function returns the topmost element in a queue. Thus, we simply return the head node of the linked list, pointing to the beginning of the queue.

#peek Function to return the topmost element
def peek(self):
    if self.isEmpty():
         return "The Queue does not exist."
    else:
         return self.LinkedList.head

#Example
tempQueue = Queue()
tempQueue.enqueue(1)
tempQueue.enqueue(2)
tempQueue.enqueue(3)
print(tempQueue.peek())

#Output
1

delete

To delete an entire queue built using a linked list, we set the head and tail references to None and free up the memory space.

#delete Function to the entire Queue
def delete(self):
     self.LinkedList.head = None
     self.LinkedList.tail = None

#Example
tempQueue = Queue()
tempQueue.enqueue(1)
tempQueue.enqueue(2)
tempQueue.enqueue(3)
tempQueue.delete

Time and Space complexity of Operations on Queue built using Linked List

Time ComplexitySpaceComplexity
Create QueueO(1)O(1)
EnqueueO(n)O(1)
DequeueO(n)O(1)
PeekO(1)O(1)
isEmptyO(1)O(1)
Delete Entire QueueO(1)O(1)

Circular Queue creation

A circular queue is an extension of the regular queue data structure where the last element is connected to the first element. This forms a circle-like structure.

The circular queue solves the limitations of the normal queue. In a normal queue, there will be non-usable space after a few insertions and deletions. However, in a circular queue, the size is limited and insertion and deletion become much more efficient.

The circular queue works in the following manner:

  • Two pointers Front and Rear.
  • Front keeps track of the first element of the queue.
  • Rear keeps track of the last element of the queue.
  • The values of Front and Rear are initially set to -1.
#Creating Circular Queue class
class CQueue:
      def __init__(self, maxSize):
        self.items = maxSize * [None]
        self.maxSize = maxSize
        self.front = -1
        self.rear = -1

#Modifying the __str__ function to return the desired string version of Circular Queue
      def __str__(self):
        values = [str(x) for x in self.items]
        return ' '.join(values)

Operations on Circular Queue

isFull

The isFull function is used to check whether the circular queue is fully occupied or not. We return a boolean value of True if the max occupancy of the circular queue has been reached, otherwise False.

#isFull function to check whether the queue is full or not
def isFull(self):
    if self.rear + 1 == self.front:
         return True
    elif self.front == 0 and self.rear + 1 == self.maxSize:
         return True
    else:
         return False

#Example
tempQueue = CQueue(3)
print(tempQueue.isFull())

#Output
False

isEmpty

The isEmpty function is used to check whether the given circular queue is empty or not. If there are no elements in the queue, we return a boolean value of True, otherwise False.

#isEmpty function to check whether the queue is empty or not
def isEmpty(self):
    if self.top == -1:
        return True
    else:
        return False

#Example
tempQueue = CQueue(3)
print(tempQueue.isFull())

#Output
True

enqueue

The enqueue function is used to insert elements at the end of a circular queue. If the max size of the queue has been reached, we terminate the process of insertion. After insertion, the newly added last element and the first element are connected via pointers to satisfy the property of the circular queue.

#enqueue Function to insert elements 
def enqueue(self, value):
        if self.isFull():
            return "The circular queue is full"
        else:
            if self.rear + 1 == self.maxSize:
                self.rear = 0
            else:
                self.rear += 1
                if self.front == -1:
                    self.front = 0
            self.items[self.rear] = value
            return "The element is successfully inserted at the end of the Circular Queue"

#Example
tempQueue = CQueue(3)
tempQueue.enqueue(1)
tempQueue.enqueue(2)
tempQueue.enqueue(3)
print(tempQueue)

#Output
1 2 3

dequeue

The dequeue function is used to delete elements from the beginning of a circular queue. After deletion of the head node, we set the head pointer to the next node in the queue and interconnect it with the last element.

#dequeue Function to insert elements 
def dequeue(self):
    if self.isEmpty():
        return "The circular queue is empty."
    else:
        firstElement = self.items[self.front]
        front = self.front
        if self.front == self.rear:
            self.front = -1
            self.rear = -1
        elif self.front + 1 == self.maxSize:
            self.front = 0
        else:
            self.front += 1
        self.items[front] = None
        return firstElement

#Example
tempQueue = CQueue(3)
tempQueue.enqueue(1)
tempQueue.enqueue(2)
tempQueue.enqueue(3)
tempQueue.dequeue()
print(tempQueue)

#Output
2 3

peek

The peek function is used to return the topmost element of the queue. In the circular queue, we do this by simply printing the value of the front node.

#peek Function to return the topmost element
def peek(self):
    if self.isEmpty():
         return "There is not any element in the Queue"
    else:
         return self.items[self.front]

#Example
tempQueue = CQueue(3)
tempQueue.enqueue(1)
tempQueue.enqueue(2)
tempQueue.enqueue(3)
print(tempQueue.peek())
print(tempQueue)

#Output
1

delete

To delete an entire circular queue, we set the front and rear references of the linked list to None. Hence, we free up the allocated space in memory.

#delete Function to the entire queue.
def delete(self):
    self.items = self.maxSize * [None]
    self.rear = -1
    self.front = -1

#Example
tempQueue = CQueue(3)
tempQueue.enqueue(1)
tempQueue.enqueue(2)
tempQueue.enqueue(3)
tempQueue.delete()

Time and Space Complexity for Operations on Circular Queue

Time ComplexitySpaceComplexity
Create QueueO(1)O(n)
EnqueueO(1)O(1)
DequeueO(1)O(1)
PeekO(1)O(1)
isEmpty/isFullO(1)O(1)
Delete Entire QueueO(1)O(1)

Interview Questions on Queue

Design a queue class which implements queue using two stacks.

#Implementing queue using two stacks
class Stack():
    def __init__(self):
        self.list = []

    def __len__(self):
        return len(self.list)

    def push(self, item):
        self.list.append(item)

    def pop(self):
        if len(self.list) == 0:
            return None
        return self.list.pop()


class QueueviaStack():
    def __init__(self):
        self.in_Stack = Stack()
        self.out_Stack = Stack()

    def enqueue(self, item):
        self.in_Stack.push(item)

    def dequeue(self):
        while len(self.in_Stack):
            self.out_Stack.push(self.in_Stack.pop())
        result = self.out_Stack.pop()
        while len(self.out_Stack):
            self.in_Stack.push(self.out_Stack.pop())
        return result


temp_queue = QueueviaStack()
temp_queue.enqueue(1)
temp_queue.enqueue(2)
temp_queue.enqueue(3)
print(temp_queue.dequeue())
temp_queue.enqueue(4)
print(temp_queue.dequeue())

#Output
1
2

An animal shelter operating strictly on “First-In/First-Out” basis holds only dogs and cats. People can select either a dog or a cat (and will recieve the oldest animal, based on arrival, of that type) or can take the oldest animal. Design a data structure to maintain this system, which includes functions such as enqueue, dequeueAny, dequeueDog, and dequeueCat.

#Implementing the AnimalShelter data structure
class AnimalShelter():
    def __init__(self):
        self.cats = []
        self.dogs = []

    def enqueue(self, animal, type):
        if type == 'Cat':
            self.cats.append(animal)
        else:
            self.dogs.append(animal)

    def dequeueCat(self):
        if len(self.cats) == 0:
            return None
        else:
            cat = self.cats.pop(0)
            return cat

    def dequeueDog(self):
        if len(self.dogs) == 0:
            return None
        else:
            dog = self.dogs.pop(0)
            return dog

    def dequeueAny(self):
        if len(self.cats) == 0:
            result = self.dogs.pop(0)
        else:
            result = self.cats.pop(0)
        return result


temp_queue = AnimalShelter()
temp_queue.enqueue('Cat1', 'Cat')
temp_queue.enqueue('Cat2', 'Cat')
temp_queue.enqueue('Dog1', 'Dog')
temp_queue.enqueue('Cat3', 'Cat')
temp_queue.enqueue('Dog2', 'Dog')
print(temp_queue.dequeueAny())

#Output
Cat1

FAQ Questions:

How to Implement a Queue in Python?

The queue is a linear data structure, that stores elements in a First In First Out order (FIFO). The class Queue has enqueue() and dequeue() function to insert and delete elements from the queue.

class Queue:
    def __init__(self):
        self.items = []
    def __str__(self):
        values = [str(x) for x in self.items]
        return ' '.join(values)
    def isEmpty(self):
        if self.items == []:
            return True
        else:
            return False
    def enqueue(self, value):
        self.items.append(value)
        return "The element is successfully inserted at the end of Queue."
    def dequeue(self):
        if self.isEmpty():
            return "The Queue does not exist."
        else:
            return self.items.pop(0)
tempQueue = Queue()
tempQueue.enqueue(1)
tempQueue.enqueue(2)
tempQueue.enqueue(3)
tempQueue.enqueue(4)
print("Initially the queue contains",tempQueue)
print(tempQueue)
print("After deque of 2 elements")
tempQueue.dequeue()
tempQueue.dequeue()
print(tempQueue)

Output

Initially the queue contains 1 2 3 4
1 2 3 4
After deque of 2 elements
3 4
How to Import Queue in Python?

Python has a module named queue which can be imported using import queue. The put() method is used to insert elements into the queue. The get() method is used to get and remove the element from the queue.

#Reusing already created queue
import queue
L = queue.Queue(maxsize=20)
L.put("Welcome")
L.put("To")
L.put("Pythonwife")
L.put("Website")
print(L.get())
print(L.get())
print(L.get())
print(L.get())

Output

Welcome
To
Pythonwife
Website
How to Implement Priority Queue in Python?

The PriorityQueue class has an insert() function to insert elements into the queue. The delete() function is used to remove elements based on priority from the queue.

class PriorityQueue(object):
	def __init__(self):
		self.queue = []

	def __str__(self):
		return ' '.join([str(i) for i in self.queue])
    
	def isEmpty(self):
		return len(self.queue) == 0

	def insert(self, data):
		self.queue.append(data)

	def delete(self):
		try:
			max = 0
			for i in range(len(self.queue)):
				if self.queue[i] > self.queue[max]:
					max = i
			item = self.queue[max]
			del self.queue[max]
			return item
		except IndexError:
			print()
			exit()
            
myQueue = PriorityQueue()
myQueue.insert(10)
myQueue.insert(100)
myQueue.insert(90)
myQueue.insert(70)
print("The queue elements are", myQueue)
print("Deleting elements based on priority : ")
while not myQueue.isEmpty():
    print(myQueue.delete())

Output

The queue elements are 10 100 90 70
Deleting elements based on priority : 
100
90
70
10
How to Print a Queue in Python?

By passing the queue variable to the print() function we can print a queue.

tempQueue = Queue()
tempQueue.enqueue("technology")
tempQueue.enqueue("hope")
tempQueue.enqueue("knowledge")
tempQueue.enqueue("trust")
print("The queue contains")
print(tempQueue)

Output

The queue contains
technology hope knowledge trust
How to Initialize a Queue in Python?

The queue can be initialized using enqueue() function.

tempQueue = Queue()
tempQueue.enqueue("technology")
tempQueue.enqueue("hope")
tempQueue.enqueue("knowledge")
tempQueue.enqueue("trust")
print("The queue contains")
print(tempQueue)

Output

The queue contains
technology hope knowledge trust
How to Initilize a Queue Filled with Zeros in Python?

Enqueueing the queue with zeros is as simple as multiplying the value 0 by the number of times 0 needs to be filled in the queue.

tempQueue = Queue()
print("Now the queue contains")
tempQueue.enqueue('0'*16)
print(tempQueue)

Output

Now the queue contains
0000000000000000
When to Use Heapq in Python?

The heapq library can be used to implement heap queue.

  • The heapify() function is used to convert list to heap.
  • The heappush() function is used to push elements to the heap.
  • The heappop() function is used to pop element from the heap.
import heapq
li = [5, 7, 9, 1, 3]
heapq.heapify(li)
print ("The created heap is : ",end="")
print (li)
heapq.heappush(li,4)
heapq.heappush(li,0)
print ("The modified heap after push is : ",end="")
print (li)
print ("The popped and smallest element is : ",end="")
print (heapq.heappop(li))

Output

The created heap is : [1, 3, 9, 7, 5]
The modified heap after push is : [0, 3, 1, 7, 5, 9, 4]
The popped and smallest element is : 0
How to Delete a Queue using Deque in Python?

The pop() function from deque library is used to delete the element from the right. Similarly popleft() is used to delete the element from the left.

import collections
DoubleEnded = collections.deque(["Sun","Mon","Tue","Wed","Thurs"])
print (DoubleEnded)

print("Removing from the right: ")
DoubleEnded.pop()
print (DoubleEnded)

print("Removing from the left: ")
DoubleEnded.popleft()
print (DoubleEnded)

Output

deque(['Sun', 'Mon', 'Tue', 'Wed', 'Thurs'])
Removing from the right: 
deque(['Sun', 'Mon', 'Tue', 'Wed'])
Removing from the left: 
deque(['Mon', 'Tue', 'Wed'])
How to Update Priority Queue in Python?

The user-defined update() function in PriorityQueue class is used to update the elements in the priority queue.

class PriorityQueue(object):
	def __init__(self):
		self.queue = []

	def __str__(self):
		return ' '.join([str(i) for i in self.queue])

	def insert(self, data):
		self.queue.append(data)

	def update(self,data,key):
		try:
			for i in range(len(self.queue)):
				if self.queue[i] == data:
					self.queue[i]=key
		except IndexError:
			print()
			exit()            
            
myQueue = PriorityQueue()
myQueue.insert(10)
myQueue.insert(100)
myQueue.insert(90)
myQueue.insert(70)
print("The queue elements are", myQueue)
myQueue.update(10,800)
myQueue.update(70,20)
myQueue.update(90,60)
print("The queue elements after replace", myQueue)

Output

The queue elements are 10 100 90 70
The queue elements after replace 800 100 60 20
How to Sort a Queue in Python?

The user-defined sortqueue() function can be used to sort the elements in the queue.

def FrontToLast(q, qsize) :
	if qsize <= 0:
		return
	q.put(q.get())
	FrontToLast(q, qsize - 1)
    
def pushInQueue(q, temp, qsize) :
	if q.empty() or qsize == 0:
		q.put(temp)
		return

	elif temp <= q.front() :
		q.put(temp)
		FrontToLast(q, qsize)

	else :
		q.put(q.get())
		pushInQueue(q, temp, qsize - 1)
def sortQueue(q):
	if q.empty():
		return
	temp = q.get()
	sortQueue(q)
	pushInQueue(q, temp, q.size())
    
qu = Queue()
qu.put(10)
qu.put(70)
qu.put(126)
qu.put(90)
qu.put(200)
qu.put(50)
sortQueue(qu)
while not qu.empty():
	print(qu.get(), end = ' ')

Output

The sorted queue is
10 50 70 90 126 200 
How to implement a Queue using Array in Python?

The following Queue class is used to implement a queue using an array.

class Queue:
	def __init__(self, c):
		
		self.queue = []
		self.front = self.rear = 0
		self.capacity = c
        
	def queueEnqueue(self, data):
		if(self.capacity == self.rear):
			print("\nQueue is full")
		else:
			self.queue.append(data)
			self.rear += 1

	def queueDequeue(self):
		if(self.front == self.rear):
			print("Queue is empty")
		else:
			x = self.queue.pop(0)
			self.rear -= 1

	def queueDisplay(self):
		if(self.front == self.rear):
			print("\nQueue is Empty")
		for i in self.queue:
			print(i, " ", end = '')
            
if __name__=='__main__':
	q = Queue(4)
	q.queueEnqueue(20)
	q.queueEnqueue(30)
	q.queueEnqueue(40)
	q.queueEnqueue(50)
	q.queueDisplay()
	q.queueDequeue()
	q.queueDequeue()
	print("\n\nafter two node deletion\n")
	q.queueDisplay()

Output

20  30  40  50  

after two node deletion

40  50  
How to take Two Stacks to Simulate the Functionality of a Queue in Python?

The Queue2Stacks class uses two objects of Stack class to implement the functionality of queue like enqueue() and dequeue()

class Stack:

    def __init__(self):
        self.items = []

    def push(self, item):
        self.items.append(item)

    def pop(self):
        return self.items.pop()

    def size(self):
        return len(self.items)

    def is_empty(self):
        return self.items == []

class Queue2Stacks(object):

    def __init__(self):
        self.in_stack = Stack()
        self.out_stack = Stack()

    def enqueue(self, item):
        self.in_stack.push(item)

    def dequeue(self):

        if self.out_stack.is_empty:
            while self.in_stack.size()>0:
                self.out_stack.push(self.in_stack.pop())
        return self.out_stack.items.pop()

q = Queue2Stacks()
for i in range(1,7):
    q.enqueue(i)
for i in range(6):
    print(q.dequeue())

Output

1
2
3
4
5
6
How to Check if a Queue is Empty using Python?

The user-defined isEmpty() function can be used to check if a queue is empty or not.

def isEmpty(self):
    if self.items == []:
        return "Empty"
    else:
        return "Not Empty"

tempQueue = Queue()
print("Now the queue is ", tempQueue.isEmpty())
tempQueue.enqueue("technology")
tempQueue.enqueue("hope")
tempQueue.enqueue("knowledge")
tempQueue.enqueue("trust")
print("The queue contains")
print(tempQueue)
print("Now the queue is ", tempQueue.isEmpty())

Output

Now the queue is  Empty
The queue contains
technology hope knowledge trust
Now the queue is  Not Empty
How to Empty a Queue in Python?

The user-defined clear() function calls isEmpty() function until all the elements in the queue is deleted.

def isEmpty(self):
    if self.items == []:
        return True
    else:
        return False
    
def clear(self):
        while(self.isEmpty()==False):
            self.dequeue()
            
tempQueue = Queue()
tempQueue.enqueue("technology")
tempQueue.enqueue("hope")
tempQueue.enqueue("knowledge")
tempQueue.enqueue("trust")
print("The queue contains")
print(tempQueue)
tempQueue.clear()
print(tempQueue.isEmpty())

Output

The queue contains
technology hope knowledge trust
True
How to Get the Content of a Queue without Removing it in Python?

In the in-built queue library, the indexing method can be used to get the content of the queue without removing it.

import queue
L = queue.Queue(maxsize=20)
L.put("Welcome")
L.put("To")
L.put("Pythonwife")
L.put("Website")
print(L.queue[0])
print(L.queue[2])

Output

Welcome
Pythonwife
How to Get Thread Number in Joinable Queue using Python?

The task_done() and join() methods can be used to get the thread number in the joinable queue.

import multiprocessing

def worker(q):
    print(q.get())
    q.task_done()
    
queue = multiprocessing.JoinableQueue()
process1 = multiprocessing.Process(
    target=worker, args=[queue])
process2 = multiprocessing.Process(
    target=worker, args=[queue])
process1.start()
process2.start()
queue.put("task 1")
queue.put("task 2")
queue.join()
print("task complete")

Output

task 1
task 2
task complete
How to Check if an Element is Present in Queue or not using Python?

The user-defined function check() in the class Queue, can be used to check if an element is present in a queue or not.

def check(self, key):
        try:
            for i in range(len(self.items)):
                if self.items[i] == key:
                    return self.items[i]+" is found"
            return key +" is not found"
        except IndexError:
            print()
            exit()

tempQueue = Queue()
tempQueue.enqueue("technology")
tempQueue.enqueue("hope")
tempQueue.enqueue("knowledge")
tempQueue.enqueue("trust")
print(tempQueue.check("hope"))
print(tempQueue.check("sample"))

Output

hope is found
sample is not found
How to Kill a Thread Blocked on a Queue using Python?

To kill a thread, we can set a stop flag, which the thread will check regularly.

import threading
import time

def run(stop):
	while True:
		print('thread running')
		if stop():
				break

def main():
		stop_threads = False
		t1 = threading.Thread(target = run, args =(lambda : stop_threads, ))
		t1.start()
		time.sleep(1)
		stop_threads = True
		t1.join()
		print('thread killed')
main()

Output

thread running
thread running
thread running
thread running
thread running
thread running
...
thread killed
When to Use a Queue in a Python Program?
  • Operating Systems – often maintain queues while implementing various low-level operations such as CPU Scheduling, Disk Scheduling, etc.
  • Hardware – hardware interrupts are handled using queues.
  • Internet – Website traffic handling.
  • And all other scenarios where a First In, First Out priority has to be implemented.
How to Close Queue Thread in Python?

The stop() function can be used to close the thread queue.

import threading
import time

def run(stop):
	while True:
		print('thread running')
		if stop():
				break
				
def main():
		stop_threads = False
		t1 = threading.Thread(target = run, args =(lambda : stop_threads, ))
		t1.start()
		time.sleep(1)
		stop_threads = True
		t1.join()
		print('thread stopped')
main()

Output

thread running
thread running
thread running
...
thread stopped
How to Implement Priority Queue with Heap in Python?

The priority queue can be implemented with heap using the heapq module. The heapq module implements the heap queue algorithm.

import heapq as hq
list_stu = [(5, 'Rihan'), (1, 'Alen'), (3, 'Moana'), (2, 'Catherin'), (4, 'Lucy')]
hq.heapify(list_stu)
print("The order of presentation is :")
for i in list_stu:
    print(i[0], ':', i[1])

Output

The order of presentation is :
1 : Alen
2 : Catherin
3 : Moana
5 : Rihan
4 : Lucy
How to Insert Elements into a Queue in Python?

The enqueue() function in the Queue class can be used to insert elements into a queue.

def enqueue(self, value):
    self.items.append(value)
    return "The element is successfully inserted at the end of Queue."

tempQueue = Queue()
tempQueue.enqueue("technology")
tempQueue.enqueue("hope")
tempQueue.enqueue("knowledge")
tempQueue.enqueue("trust")
print("The queue contains")
print(tempQueue)

Output

The queue contains
technology hope knowledge trust
What is Happens when We try to Dequeue an Empty Queue?
def enqueue(self, value):
        self.items.append(value)
        return "The element is successfully inserted at the end of Queue."
def dequeue(self):
        if self.isEmpty():
            return "The Queue does not exist."
        else:
            return self.items.pop(0)
tempQueue = Queue()
tempQueue.enqueue(10)
tempQueue.enqueue(20)
print(tempQueue.dequeue())
print(tempQueue.dequeue())
print(tempQueue.dequeue())

Output

10
20
The Queue does not exist.
How to Get Value from the Priority Queue in Python?

The PriorityQueue module has put() function to add elements to the priority queue and the get() function is used to get the values from the priority queue.

from queue import PriorityQueue
q = PriorityQueue()
q.put((10,'alen'))
q.put((30, 'elon'))
q.put((34, 'ken'))
q.put((50, 'sam'))
q.put((19, 'ben'))
print(q.get())
print(q.get())

Output

(10, 'alen')
(19, 'ben')
How to Add a Queue Elements to a process of Multiprocessing in Python?

The put() function can be used to add elements to the queue. The put() function is available in the Queue module of multiprocessing.

from multiprocessing import Queue

animals = ['dog', 'cat', 'cow', 'goat']
queue = Queue()
print('pushing items to queue:')
for sample in animals:
    print(sample)
    queue.put(sample)

Output

pushing items to queue:
dog
cat
cow
goat
How to Check if a Queue is Full in Python?

The full() function in the queue module is used to check if a queue is full or not. This function returns true, if the queue is full else returns false.

import queue
 
q = queue.Queue(6) 
q.put(1) 
q.put(2)
print(q.full())
q.put(2)
q.put(2)
q.put(2)
q.put(2)
print(q.full())

Output

False
True
How to Add Elements to a List present in a Queue using Python deque?

The append() and appendleft() functions in the deque library can be used to add elements to the left side and left side of the list present in a queue.

import collections
de = collections.deque([10,20,30])
de.append(40)
print ("The deque after appending at right is : ")
print (de)
de.appendleft(60)
print ("The deque after appending at left is : ")
print (de)

Output

The deque after appending at right is : 
deque([10, 20, 30, 40])
The deque after appending at left is : 
deque([60, 10, 20, 30, 40])
How to Insert Integer into Priority Queue in Python?

By passing the integer value to the insert() function in the priorityQueue class, Integer values can be inserted into the priority queue.

myQueue = PriorityQueue()
myQueue.insert(10)
myQueue.insert(100)
myQueue.insert(90)
myQueue.insert(70)
myQueue.insert(1234)
print("The queue elements are", myQueue)

Output

The queue elements are 10 100 90 70 1234
How to Pass a List as an Element to the Queue in Python?

The list element is passed to the enqueue() function in the Queue class to add a list to the queue.

tempQueue = Queue()
tempQueue.enqueue(["technology", "knowledge", "patience"])
samplelist=[1, 2, 3, 4]
tempQueue.enqueue(samplelist)
print("The queue contains")
print(tempQueue)

Output

The queue contains
['technology', 'knowledge', 'patience'] [1, 2, 3, 4]
How to Move Elements from Array to Queue in Python?

The len() is used to find the length of the array and the for loop is used to iterate through the array from the first element to the last element. Each array element is passed to the enqueue() function using the array index.

tempQueue = Queue()
sample=[10,20,30,40,50,60]
for i in range(len(sample)):
    tempQueue.enqueue(sample[i])
print("The queue contains")
print(tempQueue)

Output

The queue contains
10 20 30 40 50 60
How can I get All the Items that are in a Priority Queue using Python?

The get() method in the PriorityQueue module is used to get all the items in a priority queue.

from queue import PriorityQueue

rank_holders = PriorityQueue()
rank_holders.put((3, 'Paul'))
rank_holders.put((1, 'Miles'))
rank_holders.put((2, 'Dani'))

while not rank_holders.empty():
	item = rank_holders.get()
	print(item)

Output

(1, 'Miles')
(2, 'Dani')
(3, 'Paul')
How to Pass a Queue by Reference in Python?

The queue can be passed as a reference in a multi-threading python program.

from queue import Queue
from threading import Thread
import copy

_sentinel = object()

def increment(i):
    i += 1
    return i

def producer(out_q):
    i = 0
    while True:
        i = increment( i )
        print(i)
        out_q.put(i)
        if i > 5:
            out_q.put(_sentinel)
            break
            
def consumer(in_q):
    for data in iter(in_q.get, _sentinel):
        # Process the data
        pass
    
q = Queue()
t1 = Thread(target=consumer, args=(q,))
t2 = Thread(target=producer, args=(q,))
t1.start()
t2.start()

Output

1
2
3
4
5
6
What are Queue and Deque in Python?

Python queue is a built-in library that allows you to create a list that follows the first-in, first-out (FIFO) rule. Deque is a double-ended queue in which we can add and remove elements from the beginning or end of the queue. Deques follow LIFO.

from queue import Queue
waitlist = Queue()
waitlist.put('Erin')
waitlist.put('Samantha')
waitlist.put('Joe')
print(waitlist.get())

from collections import deque
waitlist = deque()
waitlist.append('Erin')
waitlist.append('Samantha')
waitlist.append('Joe')
print("Before poping : ", waitlist)
waitlist.popleft()
print("After poping : ", waitlist)

Output

Erin
Before poping :  deque(['Erin', 'Samantha', 'Joe'])
After poping :  deque(['Samantha', 'Joe'])
How to Handle Synchronization with a Queue in Python?

The join() function can be used to handle synchronization with the queue.

import threading, queue

q = queue.Queue()

def worker():
    while True:
        item = q.get()
        print(f'Working on {item}')
        print(f'Finished {item}')
        q.task_done()

threading.Thread(target=worker, daemon=True).start()

for item in range(6):
    q.put(item)
print('All task requests sent\n', end='')

q.join()
print('All work completed')

Output

All task requests sent
Working on 0
Finished 0
Working on 1
Finished 1
Working on 2
Finished 2
Working on 3
Finished 3
Working on 4
Finished 4
Working on 5
Finished 5
All work completed
How to Add Item to the Top of the Queue in Python?

With a queue, the elements can be added only at the end. If we want to add an element in the top(front) we have to use deque. The appendleft() function in the deque module can be used to add items to the Top of the Queue.

from collections import deque
Q=deque([20,1,45,77,4,23])
print("Before adding to the top", Q)
Q.appendleft(800)
print("After adding to the top", Q)

Output

Before adding to the top deque([20, 1, 45, 77, 4, 23])
After adding to the top deque([800, 20, 1, 45, 77, 4, 23])
How to Expand an Array in Queue Class using Python?
class Queue:

	def __init__(self, capacity):
		self.front = self.size = 0
		self.rear = capacity -1
		self.Q = [None]*capacity
		self.capacity = capacity

	def isFull(self):
		return self.size == self.capacity
    
	def isEmpty(self):
		return self.size == 0

	def EnQueue(self, item):
		if self.isFull():
			print("Full")
			return
		self.rear = (self.rear + 1) % (self.capacity)
		self.Q[self.rear] = item
		self.size = self.size + 1
		print("% s enqueued to queue" % str(item))

	def DeQueue(self):
		if self.isEmpty():
			print("Empty")
			return
		
		print("% s dequeued from queue" % str(self.Q[self.front]))
		self.front = (self.front + 1) % (self.capacity)
		self.size = self.size -1

	def que_front(self):
		if self.isEmpty():
			print("Queue is empty")

		print("Front item is", self.Q[self.front])
        
	def que_rear(self):
		if self.isEmpty():
			print("Queue is empty")
		print("Rear item is", self.Q[self.rear])
        
if __name__ == '__main__':
	queue = Queue(3)
	queue.EnQueue(10)
	queue.EnQueue(20)
	queue.EnQueue(30)
	queue.EnQueue(40)
	queue.DeQueue()
	queue.que_front()
	queue.que_rear()

Output

10 enqueued to queue
20 enqueued to queue
30 enqueued to queue
Full
10 dequeued from queue
Front item is 20
Rear item is 30
Does Python have an in-built module for Priority Queue?

Yes, Python has a module called PriorityQueue. The put() and get() functions in the priority queue module are used to add and remove elements from the queue.

from queue import PriorityQueue

rank_holders = PriorityQueue()
rank_holders.put((3, 'Paul'))
rank_holders.put((1, 'Miles'))
rank_holders.put((2, 'Dani'))

while not rank_holders.empty():
	item = rank_holders.get()
	print(item)

Output

(1, 'Miles')
(2, 'Dani')
(3, 'Paul')
How to Queue Server Messages in Socket Programming in Python?
import socket
from threading import Thread
import queue
import time
import logging

logging.basicConfig(level=logging.DEBUG, format='(%(threadName)-9s) %(message)s',)

BUFFER_SIZE = 20
commands_queue = queue.PriorityQueue(BUFFER_SIZE)

class Command(object):
    def __init__(self, priority, data, conn):
        self.priority = priority
        self.data = data
        self.conn = conn

    def __cmp__(self, other):
        return cmp(self.priority, other.priority)


class CommandsThread(Thread):
    def __init__(self, group=None, target=None, name=None,
                 args=(), kwargs=None, verbose=None):
        Thread.__init__(self)
        self.target = target
        self.name = name


    def run(self):
        while True:
            if not commands_queue.empty():
                command = commands_queue.get()
                logging.debug("Queueing data: " + command.data)
                time.sleep(3)
                logging.debug("Finshed queue: " + command.data)
                command.conn.send("Done: " + command.data)  # echo

# Multithreaded Python server : TCP Server Socket Thread Pool
class ClientThread(Thread):
    def __init__(self, conn, ip, port):
        Thread.__init__(self)
        self.conn = conn
        self.ip = ip
        self.port = port
        print("[+] New server socket thread started for " + ip + ":" + str(port))

    def run(self):
        while True:
            data = conn.recv(2048)
            print("Server received data:", data)
            if not commands_queue.full():
                if data.startswith("a"):
                    commands_queue.put(Command(1, data, self.conn))
                else:
                    commands_queue.put(Command(2, data, self.conn))
                # conn.send("Done: " + data)  # echo


# Multithreaded Python server : TCP Server Socket Program Stub
TCP_IP = '0.0.0.0'
TCP_PORT = 2004


tcpServer = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpServer.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
tcpServer.bind((TCP_IP, TCP_PORT))
threads = []

c = CommandsThread(name='commands')
c.start()
threads.append(c)

while True:
    tcpServer.listen(4)
    print("Multithreaded Python server : Waiting for connections from TCP clients...")
    (conn, (ip, port)) = tcpServer.accept()
    newthread = ClientThread(ip, port)
    newthread.start()
    threads.append(newthread)

for t in threads:
    t.join()

Output

Multithreaded Python server : Waiting for connections from TCP clients...
How to Make Priority Queue to Prioritize based on Two Parameters in Python?

To prioritize the priority queue based on two parameters, two parameters are passed as integers.

from queue import PriorityQueue
priority_queue = PriorityQueue()
priority_queue.put((1, 2))
priority_queue.put((1, 1))
priority_queue.put((3, 1))
priority_queue.put((2, 1))
priority_queue.put((1, 3))
print(priority_queue.get())
print(priority_queue.get())
print(priority_queue.get())
print(priority_queue.get())
print(priority_queue.get())

Output

(1, 1)
(1, 2)
(1, 3)
(2, 1)
(3, 1)
What is the Difference between a Circular Queue and a Priority Queue in Python?
CIRCULAR QUEUEPRIORITY QUEUE
The circular queue is not linear but circular.Priority Queue is a special type of data structure in which items can be inserted or deleted based on priority.
Items can be inserted or deleted from a queue in O(1) time.It can perform three operations like insert delete and display.
It is also called a ring buffer.It is also called a simple queue.
The front and back pointers both wrap around to the beginning of the array.It does not allow elements in a sorted array.
It does not allow duplicate elementsIt allows duplicate elements.
It requires less memory.It requires more memory.
More efficientLess Efficient.
How to Declare Global Queue in Python?

The queue is declared globally above all the functions. The globally declared queue can be accessed everywhere within the python program.

import queue

q = queue.Queue(4) 
def insert():
    q.put(10) 
    q.put(40)
    q.put(30)
    q.put(20)

def checkfull():
    if(q.full()):
        return True
    else:
        return False

insert()
print(checkfull())
print(q.get())
print(q.get())
print(q.get())
print(checkfull())

Output

True
10
40
30
False
How to Peek a Queue in Python?

The user-defined peek() function returns the element at the front of the queue without removing it.

class Queue:
    def peek(self):
        if self.isEmpty():
            print("Queue UnderFlow!! Terminating process.")
            exit(1)
 
        return self.q[self.front]
 
if __name__ == '__main__':
    q = Queue(5)
    q.append(10)
    q.append(20)
    q.append(30)
    print("The front element is", q.peek())

Output

Inserting element… 10
Inserting element… 20
Inserting element… 30
The front element is 10
How to Use Queue Between Threads in Python?

Create a Queue instance that is shared by all threads to achieve this. Threads then use the put() and get() functions to add or remove items from the queue.

from queue import Queue
from threading import Thread

def producer(out_q):
	while True:
		out_q.put(data)

def consumer(in_q):
	while True:
		data = in_q.get()

q = Queue()
t1 = Thread(target = consumer, args =(q, ))
t2 = Thread(target = producer, args =(q, ))
t1.start()
t2.start()

Output

Queue instances already have all of the required lockings, so they can be safely shared by as many threads as per requirement.

How to Union All Values in the Queues Without using the Get function in Python?

All the elements in the two different queues are enqueued into the resultant queue to union all the elements.

tempQueue = Queue()
sample=Queue()
result = Queue()
tempQueue.enqueue("technology")
tempQueue.enqueue("hope")
sample.enqueue("knowledge")
sample.enqueue("trust")
result.enqueue(tempQueue)
result.enqueue(sample)
print("The queue contains")
print("Queue 1 : ", tempQueue)
print("Queue 2 : ", sample)
print("Resultant Queue : ", result)

Output

The queue contains
Queue 1 :  technology hope
Queue 2 :  knowledge trust
Resultant Queue :  technology hope knowledge trust
What does Front Do in a Queue using Python?

A queue is an ordered collection of items where the addition of new items happens at one end, called the “rear”, and the removal of existing items occurs at the other end, commonly called the “front”.

We can write a function to get the element in the front, the function name could be different based on user preferences, some people use the function name front(), but the majority of the people use peek() function to get the element in the front.

class Queue:
#def front(self) can also be used
def peek(self):
    if self.isEmpty():
        print("Queue UnderFlow!! Terminating process.")
        exit(1)
 
    return self.q[self.front]
 
if __name__ == '__main__':
    q = Queue(5)
    q.append(10)
    q.append(20)
    q.append(30)
    print("The front element is", q.peek())

Output

Inserting element… 10
Inserting element… 20
Inserting element… 30
The front element is 10
How to Get Summation of a all the Elements in the Queue using Python?

The user-defined findsum() method can be used to return the sum of all the elements of the queue.

def findsum(self):
        res = 0
        while(self.isEmpty() == False):
            res=res+self.dequeue()
        return res
tempQueue = Queue()
tempQueue.enqueue(10)
tempQueue.enqueue(20)
tempQueue.enqueue(30)
tempQueue.enqueue(40)
print("The queue contains")
print(tempQueue)
result = tempQueue.findsum()
print("Sum of elements:")
print(result)

Output

The queue contains
10 20 30 40
Sum of elements:
100
How to implement a Queue using Linked List in Python?

The Node class and Queue class are used to implement Queue using a linked list.

class Node:
	
	def __init__(self, data):
		self.data = data
		self.next = None
class Queue:
	
	def __init__(self):
		self.front = self.rear = None

	def isEmpty(self):
		return self.front == None

	def EnQueue(self, item):
		temp = Node(item)
		if self.rear == None:
			self.front = self.rear = temp
			return
		self.rear.next = temp
		self.rear = temp

	def DeQueue(self):
		if self.isEmpty():
			return
		temp = self.front
		self.front = temp.next
		if(self.front == None):
			self.rear = None

if __name__== '__main__':
	q = Queue()
	q.EnQueue(10)
	q.EnQueue(20)
	q.DeQueue()
	q.DeQueue()
	q.EnQueue(30)
	q.EnQueue(40)
	q.EnQueue(50)
	q.DeQueue()
	print("Queue Front " + str(q.front.data))
	print("Queue Rear " + str(q.rear.data))

Output

Queue Front 40
Queue Rear 50
How to Implement a Circular Queue Class in Python?

A circular queue is a linear data structure in which the operations are performed based on the FIFO (First In First Out) principle. The last position is connected back to the first position to make a circle. It is also called ‘Ring Buffer’

class MyCircularQueue():

    def __init__(self, k):
        self.k = k
        self.queue = [None] * k
        self.head = self.tail = -1

    def enqueue(self, data):

        if ((self.tail + 1) % self.k == self.head):
            print("The circular queue is full\n")

        elif (self.head == -1):
            self.head = 0
            self.tail = 0
            self.queue[self.tail] = data
        else:
            self.tail = (self.tail + 1) % self.k
            self.queue[self.tail] = data

    def dequeue(self):
        if (self.head == -1):
            print("The circular queue is empty\n")

        elif (self.head == self.tail):
            temp = self.queue[self.head]
            self.head = -1
            self.tail = -1
            return temp
        else:
            temp = self.queue[self.head]
            self.head = (self.head + 1) % self.k
            return temp

    def printCQueue(self):
        if(self.head == -1):
            print("No element in the circular queue")

        elif (self.tail >= self.head):
            for i in range(self.head, self.tail + 1):
                print(self.queue[i], end=" ")
            print()
        else:
            for i in range(self.head, self.k):
                print(self.queue[i], end=" ")
            for i in range(0, self.tail + 1):
                print(self.queue[i], end=" ")
            print()

temp = MyCircularQueue(5)
temp.enqueue(10)
temp.enqueue(20)
temp.enqueue(30)
temp.enqueue(40)
temp.enqueue(50)
print("Initial queue")
temp.printCQueue()
temp.dequeue()
print("After removing an element from the queue")
temp.printCQueue()

Output

Initial queue
10 20 30 40 50 
After removing an element from the queue
20 30 40 50 
How to Get the Length of a Queue in Python?

The inbuilt qsize() function can be used to get the length of a queue.

import queue
a=queue.Queue()
a.put("abcdef")
a.put(10)
a.put(20)
print("size of queue : ", a.qsize())

Output

size of queue :  3