Understand Python FIFO Queque with Examples: A Beginner Guide – Python Tutorial

By | December 20, 2019

FIFO queque is the basic data strucutre in computer science. How to implement it in python. To address this issue, in this tutorial, we will use some examples to show you understand and implement a fifo queue in python.

What is fifo queue?

FIFO queue is a queue which means first in and first out. Look at image below:

python fifo queue example

This kind of queue contains two basic operations:

Enqueue: put a data into a queue

Dequeue: get a data from a queue

How to use fifo queue in python

To use fifo queue in python correctly, these questions we must concern:

How to create a fifo queue?

How to put a data into a fifo queue?

How to get a data from a fifo queue?

We will fix these problems one by one.

How to create a fifo queue in python?

To create a fifo queque in python we can do like this:

import queue
max_size = 5
fifo=queue.Queue(max_size)

This code example means we will create a fifo queue, which will contain 5 elements at maximum.

Notice: if max_size <=0, which means this fifo queue will contains infinite elements.

How to put a data into a fifo queue in python?

To put a data into a fifo queue is very simple, we can use put() method.

fifo.put(3)
fifo.put([1, 2])
fifo.put('tutorialexample.com')

This code example will put 3 data into this fifo queue, this queue will be:

tutorialexample.com [1, 2] 3

How to get a data from a fifo queue in python?

Like put() method will insert a data into a fifo queue, we will use get() method to get a data from a fifo queue.

Here is an example:

num_1 = fifo.get()
print("first data = " + str(num_1))
print("fifo size = " + str(fifo.qsize()))

num_2 = fifo.get()
print("second data = " + str(num_2))
print("fifo size = " + str(fifo.qsize()))

num_3 = fifo.get()
print("third data = " + str(num_3))
print("fifo size = " + str(fifo.qsize()))

In this example, we will get data from fifo one by one. These data are:

first data = 3
fifo size = 2
second data = [1, 2]
fifo size = 1
third data = tutorialexample.com
fifo size = 0

From the result we can find: fifo.qsize() will return the count of data in fifo queue.

How to traverse a fifo queue?

Here is an simple example:

for i in range(4):
    fifo.put(i)
while not fifo.empty():
    print(fifo.get())

fifo.empty() will check a fifo queue contains a data or not, if it contains, this method will return True.

However, you must notice:

If the data size of you plan to put into a fifo is bigger than max size of fifo queue. The python script will be blocked.

For example:

As fifo queue above, we have created it for max_size = 5, which means it will contain 5 data at maximum. If you plan to put 10 data.

for i in range(10):
    fifo.put(i)
while not fifo.empty():
    print(fifo.get())

You will find this python script is blocked here.

Leave a Reply