What is Python Queue?

Python queue is an important concept in the data structure. Queue in Python is nothing but data item containers. With the help of a queue in Python, we can control the flow of our tasks.

Say, we are manipulating data that are collected from a website and then writing the manipulated data into a .txt file. Now, if we have not collected the data from the website, we would not be able to start the data manipulating task, right? We don’t want to save the data right after collecting it from the website to avoid messing up the workflow of the whole task. Python queue is a great way to keep things in track.

Types of Queue In Python

There are Four types of queues in Python. They are:

So, let’s get started.

Get 100% Hike!

Master Most in Demand Skills Now !

Python First-in First-out Queue

As the name suggests, in the first-in first-out queue policy, the first element that goes in comes out first. It is just like putting the element inside an open cylinder. Before we move ahead, we need to import one library called a queue. After that, we can create instances that can be viewed as containers.

Let us see how to do that.

import queue
q = queue.Queue()

This chunk of code will import the queue library and will create one instance of the queue. By default, this queue in python is of type first-in first-out (FIFO type). In the case of the FIFO queue, the item that we enter first gets out first.

Learn more about Python from an expert. Enroll in our Python training in Bangalore

Adding an item in a queue:

We can add an item into a queue in Python with the help of the python function called “put function”. This is as simple as it sounds. Let’s try that with a Python Queue example.

import queue
q = queue.Queue()
q.put(5)

This will create an instance called q where we will be adding 5.

Removing an item from a queue in Python:

To remove items from a queue in Python, we will be using the “get function”. See the Python Queue example given below.

import queue
q = queue.Queue()
q.put(9)
print(q.get()) #to print the item that we are removing

Output:9
print(q.empty())

To make sure that our queue is empty, we can use the empty function which will return Boolean values.

Output:
True

Become a Full Stack Web Developer

Adding more than one item into a queue in Python:

The real application of a queue is when there is more than one item to deal with. Let us dive into one Python Queue example where we will be adding more than one item using the FIFO method.

import queue
q = queue.Queue()
for i in range(9):
q.put(i)

This chunk of code will create one queue instance and then will add items ranging from 0 to 8.

Removing more than one item from a queue in Python:

Now that we have added items into the queue, let us see how to get them out of it.

import queue
q = queue.Queue()

for i in range(9):
q.put(i)

while not q.empty():
print(q.get(), end=” “)
print(“FIFO”)

Output:
0 FIFO
1 FIFO
2 FIFO
3 FIFO
4 FIFO
5 FIFO
6 FIFO
7 FIFO
8 FIFO

Further, Intellipaat’s industry-designed Python course will help you get a more elaborate understanding of Python concepts in detail.

Python Last-in First-out Queue

Again, as the name says, in this type of queue, the element that goes in first comes out last. In other words, the one that goes, at last, comes out first. But unlike FIFO (which is considered as the default queue type), we have to add a special function to operate LIFO queues.

Let us explore the LIFO queue with the help of an example:

import queue
q = queue.LifoQueue()

Adding an item into a queue:

Similar to what we did while understanding the FIFO type, let us add 5 to a queue.

import queue
q = queue.LifoQueue()
q.put(5)

Removing an item from a queue:

Use the same function to remove the item from the queue.

import queue
q = queue.LifoQueue()
q.put(5)
print(q.get())

But, the concept of LIFO is not visible here, isn’t it? Let us add more than one item into the queue and see which one gets out first.

Adding more than one item into a queue:

Let us add numbers from 0 to 8 into a queue.

import queue
q = queue.LifoQueue()
for i in range(9):
q.put(i)

Removing an item from a queue:

Now that we have added items into the queue, let us see which one gets out first.

import queue
q = queue.LifoQueue()

for i in range(9):
q.put(i)

while not q.empty():
print(q.get(), end=” “)
print(“LIFO”)

Output:
8 LIFO
7 LIFO
6 LIFO
5 LIFO
4 LIFO
3 LIFO
2 LIFO
1 LIFO
0 LIFO

Certification in Full Stack Web Development

Python Priority Queue

The priority queue in Python is a bit interesting one. Here, the order in which we put the items it doesn’t matter. What really matters is the value of the items. But, how is that going to work? Well, the logic behind this policy is that the lowest valued item gets out first.

Again, to be able to perform priority queue operations, we have to use another function shown below.

import queue
q= queue.PriorityQueue()

Let us see how this works with the help of an example.

Example:

Let us add 5 elements into a queue using the priority queue function.

import queue
q= queue.PriorityQueue()
q.put(2)
q.put(4)
q.put(1)
q.put(0)
q.put(2)

Now that we have the items in the queue, let us use the Python for loop to remove the items. We will be using the q.qsize() function (returns the size of the queue) in order to run the for loop function.

import queue
q= queue.PriorityQueue()
q.put(2)
q.put(4)
q.put(1)
q.put(0)
q.put(2)

for i in range(q.qsize()):
print(q.get(i))

output:
1
2
2
4

As we can see here, the item with the lowest value gets out first. But again, if two elements are of the same value, then the order is taken into consideration while removing the elements out of the Python queue.

This brings us to the end of this module in Python Tutorial. Now, if you want to know why Python is the preferred language for data science, you can go through this blog on Python Data Science tutorial.

Career Transition

Adding & Removing Items in Queue

Queue is a collection of similar items arranged in a linear order. A simple queue items are can be accessed in the First-in-First-out(FIFO). Let’s understand how to add or remove items from a LIFO queue. 

Adding Items to Queue

To add items in a queue,  put() function is used. Let’s see an example below:

import queue
#importing the class queue to create an object q
q=queue.Queue(maxsize=5)
#Put() func. is used to insert values
#values are inserted at the end of queue
q.put(5)
q.put(10)
q.put(15)
q.put(20)
q.put(25)

Removing Items from Queue

To remove an element from the queue, get() function is used. Below is an example of the same:

#get() func. will get the values
#the values are fetched from the queue head

for i in range(0,5):
    print(q.get(), end="  ")

Sorting a Queue 

Sorting means rearranging the queue items in either ascending or descending order. Below is the program used to sort the queue elements in ascending order:

import queue
q=queue.Queue()

q.put(10)
q.put(5)
q.put(15)
q.put(22)
q.put(20)
q.put(25)

size=q.qsize()

for i in range(size):
    x=q.get()
    for j in range(size-1):
        y=q.get()
        if(x>y):
            q.put(y)
        else:
            q.put(x)
            x=y

    q.put(x)

while(q.empty()==False):
    print(q.queue[0],end=" ")
    q.get()

The output of the above program will be:

5 10 15 20 22 25

Reversing Queue

Reversing will print the queue elements from right to left. Bellow is the program to do so: 

import queue
q=queue.Queue()

q.put(10)
q.put(5)
q.put(15)
q.put(22)
q.put(20)
q.put(25)

def reversequeue(q1,st):
    buff=q1.get()
    if(q1.empty()==False):
        reversequeue(q1,st)
    st.put(buff)
    return st


st=queue.Queue()
qrev=reversequeue(q,st)

size=qrev.qsize()

for i in range(size):
    print(qrev.get(),end=" ")

The output of the above program will be:

25 20 22 15 5 10

Python Circular Queue

In a circular queue, the last element is connected to the first element, forming a circle-like structure. It is an extended version of a normal queue.

A circular queue solves one of the major problems of a regular queue. In a regular queue, after some insertion and deletion, there exists empty space which is non-usable.

Here, you can use the indexes 0 and 1 only after you reset the queue by deleting all its elements. This reduces the actual size of the queue.

class CircularQueue:
  def __init__(self, maxSize):
    self.queue = list()
    self.maxSize = maxSize
    self.head = 0
    self.tail = 0
  def enqueue(self, data):
    if self.size() == (self.maxSize - 1):
      return("Queue is full!")
    else:
      self.queue.append(data)
      self.tail = (self.tail+1) % self.maxSize
      return True
  def dequeue(self):
    if self.size() == 0:
      return("Queue is empty!")
    else:
      data = self.queue[self.head]
      self.head = (self.head+1) % self.maxSize
      return data
  def size(self):
    if self.tail >= self.head:
      qSize = self.tail - self.head
    else:
      qSize = self.maxSize - (self.head - self.tail)
    return qSize

size = input("Enter the size of the Circular Queue")
q = CircularQueue(int(size))

print(q.enqueue(10))
print(q.enqueue(20))
print(q.enqueue(30))
print(q.enqueue(70))
print(q.enqueue(80))
print(q.dequeue())
print(q.dequeue())
print(q.dequeue())
print(q.dequeue())

The output will be:

Enter the size of the Circular Queue 4
4
True
True
True
Queue is full!
Queue is full!
10
20
30

Queue is empty!

Further, check out our Python interview questions by experts. Big companies like Netflix and IBM use Python. Dropbox is created in Python, and hundreds of other big companies are also adapting Python. So, this is not a surprise that Python has become one of the fastest-growing programming languages according to Stack Overflow. The ever-expanding applications of large-scale Data Science and Artificial Intelligence have become two of the most aspiring fields in the 21st century. To be a part of these competitive and most lucrative fields, one must fulfill the requirement of having a well-rounded understanding of Python.

For any doubts related to python queue or python tutorial, head to our Python Community right away!

Course Schedule

Name Date Details
Python Course 25 Mar 2023(Sat-Sun) Weekend Batch
View Details
Python Course 01 Apr 2023(Sat-Sun) Weekend Batch
View Details
Python Course 08 Apr 2023(Sat-Sun) Weekend Batch
View Details

Leave a Reply

Your email address will not be published. Required fields are marked *