Python Queue: FIFO (FIRST IN FIRST OUT), LIFO (LAST IN FIRST OUT)

What is Python Queue?

A queue is a container that holds data. The data that is entered first will be removed first, and hence a queue is also called "First in First Out" (FIFO). The queue has two ends front and rear. The items are entered from the rear and removed from the front side.
The queue can be easily compared with the real-world example the line of people waiting in a queue at the ticket counter, the person standing first will get the ticket first, followed by the next person and so on. The same logic goes for the queue data structure too.
Diagrammatic representation of queue is given below:

The Rear represents the point where the items are inserted inside the queue. In this example, 7 is value for that.
The Front represents the point where the items from the queue will be removed. If you remove an item from the queue, the first element you will get is 1, as shown in the figure.
Item 1 was the first one to be inserted in the queue, and while removing it is the first one to come out. Hence the queue is called FIRST IN FIRST OUT (FIFO)
In a queue, the items are removed in order and cannot be removed from in between. You just cannot remove the item 4 randomly from the queue, to do that you will have to remove all the items before 4. The items in queue will be removed in the order they are inserted.

There are two types of Queue in Python:

  • First in First out Queue: For this, the element that goes first will be the first to come out.
    To work with FIFO, you have to call Queue() class from queue module.
  • Last in First out Queue: Over here, the element that is entered last will be the first to come out.
    To work with LIFO, you have to call LifoQueue() class from the queue module.

    Methods available inside Queue and LifoQueue class

    Following are the important methods available inside Queue and LifoQueue class:
    • put(item): This will put the item inside the queue.
    • get(): This will return you an item from the queue.
    • empty(): It will return true if the queue is empty and false if items are present.
    • qsize(): returns the size of the queue.
    • full(): returns true if the queue is full, otherwise false.

Below is the sample program to represent queue concept in python


import queue 
L = queue.LifoQueue(maxsize=6) 
# qsize() give the maxsize of 
# the Queue 
print(L.qsize()) 
# Data Inserted as 5->9->1->7, 
# same as Queue 
L.put(5) 
L.put(9) 
L.put(1) 
L.put(7) 
L.put(9) 
L.put(10) 
print("Full: ", L.full()) 
print("Size: ", L.qsize()) 

# Data will be accessed in the 
# reverse order Reverse of that 
# of Queue 
print(L.get()) 
print(L.get()) 
print(L.get()) 
print(L.get()) 
print(L.get()) 
print("Empty: ", L.empty()) 


To be continued...