Python Queue Tutorial: How To Implement And Use Python Queue

By Sruthy

By Sruthy

Sruthy, with her 10+ years of experience, is a dynamic professional who seamlessly blends her creative soul with technical prowess. With a Technical Degree in Graphics Design and Communications and a Bachelor’s Degree in Electronics and Communication, she brings a unique combination of artistic flair…

Learn about our editorial policies.
Updated March 7, 2024

This Python Queue tutorial will discuss pros, cons, uses, types, and operations on Queues along with its implementation with programming examples:

In Python, a Queue is a linear data structure that follows the FIFO approach.

Here FIFO refers to “ First In First Out “ i.e. the first element entered in the queue will be popped out first. Or we can say that this approach is the exact opposite of the Stack data structure.

=> Explore the Python Learner’s Guide Here

Python Queue

Python Queue

Let us understand the queue with the real-world example of “ Cinema ticket counter ”. While buying the tickets for the movie, people stand in a queue at the ticket counter.

The second person or the third person will buy the ticket only if the first person or second person gets the ticket from the counter. The second person cannot break the queue to buy the ticket first.

Here the first person will buy the ticket first and only then the turn will come for the second person. The Python queue works on the above principle.

The below image depicts Python Queue.

Cinema ticket counter - FIFO Example

Advantages

  • It is easy to implement as it follows the FIFO principles.
  • Easy to insert or delete the elements in the queue.
  • Can add the new element any time in the end.

Disadvantages

  • It is not easy to delete the elements from the middle.
  • Difficult to create and maintain.
  • It is a non-linear data structure that takes a large amount of memory when compared to linear data structures.

Applications

The queue data structure is used when we want to organize the group of objects in a particular order. The second person or the thing cannot use the resources until the first person or thing releases that resource.

  • It serves the request on a single shared resource. For example, Printer, CPU, etc.
  • If we relate it with the real-world example then, the call center is one of the powerful examples of a queue.
  • If any issue occurs, it can be resolved in the FIFO order i.e. the issue which occurs first will be resolved first.

Types of Queue

#1) Python Simple Queue

In the simple queue data structure, the insertion of the element takes place at the rear and removes from the front position. It follows the FIFO criteria.

Python Simple Queue

How to use Simple Queue in Python?

```
class demo_queue:

  def __init__(self):
      self.queue = list()

  def add_demo_element(self,element):

# Add the above method to insert the element

      if element not in self.queue:
          self.queue.insert(0,element)
          return True
      return False

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

Queue = demo_queue()
Queue.add_demo_element("Monday")
Queue.add_demo_element("Tuesday")
Queue.add_demo_element("Wednesday")
print(Queue.size())

```

How to use Simple Queue in Python

#2) Python Circular Queue

In the circular queue data structure, the last element of the queue is assigned as the first element of a queue to make a circular link between the items i.e. we can add the new element at the first position.

Python Circular Queue

How to use Circular Queue in Python?

```
class CircularQueueDemo():

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

	# Add an element into the demo circular queue

	def Enqueue(self, data_elements):

    	if ((self.tail + 1) % self.a == self.head):
        print("The demo circular queue does not have more space\n")

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

	# Remove an element from the demo circular queue

	def Dequeue(self):
    	if (self.head == -1):
        print("The demo 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.a
        return temp

	def printdemoCQueue(self):
    	if(self.head == -1):
        print("No element present in the demo 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.a):
            	print(self.queue[i], end=" ")
        for i in range(0, self.tail + 1):
            	print(self.queue[i], end=" ")
        print()

obj = CircularQueueDemo(5)
obj.Enqueue(1)
obj.Enqueue(2)
obj.Enqueue(3)
obj.Enqueue(4)
obj.Enqueue(5)
print( " Demo Queue: " )
obj.printdemoCQueue()

obj.Dequeue()
print( " Demo Queue after removing the elements " )
obj.printdemoCQueue()

```

How to use Circular Queue in Python

#3) Python Priority Queue

A priority queue data structure is unique from all the other types of the queue because, in this queue, each element has its own priority according to which all the elements are served. Suppose if the two elements have the same priority then, they will be served on the basis of their order.

Python Priority Queue

How to use Priority Queue in Python?

```
class PriorityQueueDemo(object):
	def __init__(self):
    	self.queue = []
 
	def __str__(self):
    	return ' '.join([str(i) for i in self.queue])
 
	# Here we are checking whether the demo queue is empty or not

	def Is_Queue_Empty(self):
    	return len(self.queue) == 0
 
	# Adding the elements in the demo queue

	def Add_elements(self, data_elements):
    	self.queue.append(data_elements)
 
	# Removing the elements from the demo queue on the basis of their priority

	def Remove_elements(self):
    	try:
       max = 0
       for i in range(len(self.queue)):
            	if self.queue[i] > self.queue[max]:
                	max = i
        items = self.queue[max]
        del self.queue[max]
        return items
    	except IndexError:
        print()
        exit()
 
if __name__ == '__main__':
	demoQueue = PriorityQueueDemo()
	demoQueue.Add_elements(11)
	demoQueue.Add_elements(2)
	demoQueue.Add_elements(45)
	demoQueue.Add_elements(72)
	print(demoQueue)       	 
	while not demoQueue.Is_Queue_Empty():
    	print(demoQueue.Remove_elements())

```

How to use Priority Queue in Python

#4) Python Deque (Double-ended queue)

It does not follow the FIFO approach. In this queue, the addition and removal of the element take place from both sides i.e. rear and front.

Python Deque (Double-ended queue)

How to use Deque (Double-ended queue) in Python?

```
import collections

# Create a demo deque

DemoDoubleEnded = collections.deque(["Monday","Tuesday","Wednesday"])
print (DemoDoubleEnded)

# Add the element to the right position

print("Inserting to the right position: ")
DemoDoubleEnded.append("Thursday")
print (DemoDoubleEnded)

# Add the element to the left position

print("Inserting to the left position: ")
DemoDoubleEnded.appendleft("Sunday")
print (DemoDoubleEnded)

# Delete the element from the right position

print("Delete from the right position: ")
DemoDoubleEnded.pop()
print (DemoDoubleEnded)

# Delete the element from the left position

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

# Reverse the demo dequeue

print("Reversing the elements of the deque: ")
DemoDoubleEnded.reverse()
print (DemoDoubleEnded)

```

How to use Deque (Double ended queue) in Python

Operations on Queue

The basic queue operations are:

  • Enqueue: It adds the element at the end of the queue.
  • Dequeue: It deletes the element from the front of the queue.
  • IsEmpty: It checks whether the queue is empty or not.
  • IsFull: It checks whether the queue is full or not.
  • Peek: It will give the value of the front element of the queue without removing it from the queue.

Program

```
class Demo_Queue:
	def __init__(self):
    	self.items = []
	def Is_Empty(self): # This function will check whether the queue is empty or not
    	return self.items == []
	def Enqueue(self, data):
    	self.items.append(data) # here we are appending the elements in the queue
	def Dequeue(self):
    	return self.items.pop(0) # here we are performing the Dequeue operation 
demo_queue = Demo_Queue()
while True:
	print('Enqueue operation ')
	print('Dequeue operation’')
	print('Quit')
	task = input('What would you like to do? ').split()
 
	operations = task[0].strip().lower()
	if operations == 'Enqueue': # Condition
    	demo_queue.Enqueue(int(task[1]))  # Append the element in the queue
	elif operations == 'Enqueue':
    	if demo_queue.Is_empty():
        print('Demo Queue is empty.')
    	else:
        print('Dequeued value: ', demo_queue.Dequeue())
	elif operations == 'Quit':
    	break
```

Output

Operations on Queue

How to Implement Queue in Python

  • There will always be two pointers in a queue – “ Front ” and “Rear”.
  • The front will be the first element of the queue.
  • The rear will be the last element of the queue.
  • Whereas, initially Front and Rear are equal to -1.

Let us understand these operations with the below diagram.

Enqueue:

  • It will first check if the queue is full or not.
  • It will generate the overflow error and exit if the queue is full.
  • It will increment the rear pointer if the queue is not full.
  • Then, insert the element in the queue, where “ Rear ” is pointing.
  • Return output.

Enqueue

Program

```
class Demo_Queue:  
	def __init__(self):  
    	self.queue = list()  
	# Inserting the elements
	def insert_element(self,val):   
    		if val not in self.queue:  
        			self.queue.insert(0,val)  
        			return True  
    		return False  
 	 
	def size(self):  
    	return len(self.queue)  
 	 
demo_queue = Demo_Queue()  
demo_queue.insert_element("A")  
demo_queue.insert_element("B")  
demo_queue.insert_element("C")  
demo_queue.insert_element("D")  
 	 
print( " The length of Demo Queue is: ",demo_queue.size() ) 
```

In the above program, we are creating a queue and inserting the elements into it.

Output:

Enqueue output

Dequeue:

  • It will tell whether the queue is empty or not.
  • It will generate the underflow error and exit if the queue is empty.
  • We can access the front element if the queue is not empty.
  • It will increment the front pointer for the next element.
  • Return Output.

Dequeue

Program

```
demo_queue = []
demo_queue.append('S') # Adding the elements to the list
demo_queue.append('T')
demo_queue.append('H')
 
print(" Demo queue before deleting the elements")
print(demo_queue)

print("\nElements deleted from queue")
print(demo_queue.pop(0)) #Removing the elements from the list
print(demo_queue.pop(0))
print(demo_queue.pop(0))
 
print("\nDemo queue after deleting elements")
print(demo_queue)
```

In the above program, we create a demo queue and add the elements. After the insertion of elements, we delete all the elements from the queue.

Output:

Dequeue - output

Methods of Queue

Python supports the various methods of Queue, that are most commonly used while working with the queue data structure.

  • put( item ): It is used to add the element in the queue.
  • get(): It is used to delete the element from the queue.
  • empty(): It is used to check and make sure that the queue is empty.
  • qsize: It is used to calculate the length of the queue.
  • full(): It will return TRUE if the queue is full otherwise it will return FALSE.

Frequently Asked Questions

Q #1) How do you queue in Python?

Answer: In Python, to insert the element in the queue, the “ put() ” function is used. It is known as an enqueue operation.

  • To delete the element in the queue the “ get() ” function is used. It is known as the dequeue operation.
  • The Python queue works on the FIFO ( First In First Out ) principle i.e. the element which is stored first will be deleted first.

Q #2) How to use a Python queue?

Answer: To use the queue in Python “ from queue import Queue “ is used.

Here is the small program:

```
from queue import Queue

demo = Queue()
demo.size() # it will give the size of the queue
demo.empty() # it will tell whether the queue is empty or not
demo.put(item)
demo.get()

``` 

Q #3) How do I know if my queue is empty?

Answer: To check if the queue is empty or not follow the below algorithm:

  • Add the front element and store it in a variable then, initialize it with zero.
  • Pop the front element of the queue.
  • Repeat the above steps to empty the queue.
  • Then, print the output value of the variable.

Q #4) How to import queues in Python?

Answer: In Python in order to import Queue in the program, the “ import Queue ” is used.

Example

```
import queue # Here we are importing the queue class
  
demo = queue.Queue(maxsize=20) # Defining the maximum size of the queue
demo.put(4) # Elements are added into the queue using the “put()” function in the queue 
demo.put(5)
demo.put(3)
demo.put(6)

print(demo.get()) # Elements are deleted from the queue using the “get()” function from the queue
print(demo.get())
print(demo.get())
print(demo.get())

```

Q #5) How to create a queue in Python?

Answer: To create a simple Queue in Python, follow the below steps:

  • Create an empty list.
  • Start appending the elements in the list created above.
  • Use the “.append()” function to add the elements as given below.

Example:

```
demo_queue = []

demo_queue.append(‘Software’)
demo_queue.append(‘Testing’)
demo_queue.append(‘Help’)

print(“The Queue is created: ”, demo_queue)

```

Conclusion

In this tutorial, we discussed the Queue data structure. The queue is a non-linear data structure that uses the FIFO principle.

Enlisted below are the topics covered in this tutorial:

  • Advantages and Disadvantages of Queue data structure.
  • Applications of Queue
  • Types of Queue
  • Operations on Queue
  • Working of Queue

=> Read Through Python Training Tutorials Here

Was this helpful?

Thanks for your feedback!

Leave a Comment