Python queue With Examples

In our previous tutorial we have discussed about python time sleep function of the time module. In this tutorial we will learn about python queue module.

Python queue

When we want to process our data in the way they have arrived, then using queue is the best option. Queue is a concept of first in first out data structure. Have a look at the following example:

This will output:

python-lifoqueue-example

Python Queue Example code analysis

In the very first line we have imported the python queue module. Then we have created an object of Queue as the queue module contain three classes like Queue, LifoQueue and PriorityQueue.

Then we have added some value to the object of queue using put() method. Finally we have retrieved the values until the size of the q, using get() method. And if you notice the output, you will see that the outputs are as the way we have added.

Python Queue common methods

In the python queue module, the followings are the most common methods that are used to manipulate or operate on the queue objects. We have already seen three methods in the previous example. They are put(), get() and qsize(). We will see some other methods.

Python Queue full() function

To check whether a queue object is full or not. It returns true if the queue is full otherwise false.

Python Queue empty() function

If the queue is empty then it returns true otherwise false.

See the following example:

Above python queue example code will produce following output.

Python LifoQueue

Python LifeQueue is similar to queue except that it’s last-in-first-out data structure. Below is a simple python LifoQueue example code.

Below image shows the output produced by python LifoQueue example code.

python-lifoqueue-example

Python Priority Queue

Priority Queue returns the item in the order of the priority. So when we add an item to the priority queue, we also provide it’s priority. Then we retrieve items, they are returned in the order of the priority. Lower number priority items are returned first.

Below is python PriorityQueue example code.

Here is the output produced by python priority queue example program.

Python queue

Priority Queue Python heapq module

Python Queue module PriorityQueue functions are synchronized. There is another module heapq that also implements priority queue in python.

Output produced by heapq priority queue implementation example program is shown in below image.

Python queue

That’s all about Python Queue, Priority Queue and LifoQueue.

Reference: Official Doc

By admin

Leave a Reply