
👉Python Queue: FIFO and LIFO Examples with Code
A queue is a data structure that stores data elements in a specific order. In Python, the queue follows two primary principles:
- FIFO (First In First Out): The first element added is the first one removed.
- LIFO (Last In First Out): The last element added is the first one removed.
👉What is Python Queue?
A queue has two main ends:
- Front: The end where items are removed.
- Rear: The end where items are added.
👉How Does Python Queue Work?
A Python queue behaves like a real-life ticket counter queue where the person who arrives first gets served first (FIFO).
👉Types of Queue in Python
Python supports two types of queues:
- FIFO Queue: Uses Queue() class.
- LIFO Queue: Uses LifoQueue() class.
👉Python Queue Installation
The queue module is available by default in Python. Simply import it:
python
import queue
👉FIFO Queue Example
To create a FIFO queue:
python
import queue
q1 = queue.Queue()
q1.put(10) # Adding item
print(q1.get()) # Removing item
👉Output:
10
👉LIFO Queue Example
To create a LIFO queue:
python
import queue
q1 = queue.LifoQueue()
q1.put(10) # Adding item
print(q1.get()) # Removing item
👉Output:
10
👉Key Methods in Queue
- put(item): Adds an item to the queue.
- get(): Removes and returns an item from the queue.
- empty(): Returns True if the queue is empty.
- qsize(): Returns the number of items in the queue.
- full(): Returns True if the queue has reached its maximum limit.
👉Adding Multiple Items in FIFO Queue
python
import queue
q1 = queue.Queue()
for i in range(5):
q1.put(i)
while not q1.empty():
print(q1.get(), end=” “)
👉Output:
0 1 2 3 4
👉Adding Multiple Items in LIFO Queue
python
import queue
q1 = queue.LifoQueue()
for i in range(5):
q1.put(i)
while not q1.empty():
print(q1.get(), end=” “)
👉Output:
4 3 2 1 0
👉Sorting a Queue (Bubble Sort Method)
python
import queue
q1 = queue.Queue()
for item in [11, 5, 4, 21, 3, 10]:
q1.put(item)
n = q1.qsize()
for i in range(n):
x = q1.get()
for j in range(n – 1):
y = q1.get()
if x > y:
q1.put(y)
else:
q1.put(x)
x = y
q1.put(x)
while not q1.empty():
print(q1.get(), end=” “)
👉Output:
3 4 5 10 11 21
👉Reversing a Queue
python
import queue
q1 = queue.Queue()
for item in [11, 5, 4, 21, 3, 10]:
q1.put(item)
def reverseQueue(q1src, q2dest):
buffer = q1src.get()
if not q1src.empty():
reverseQueue(q1src, q2dest)
q2dest.put(buffer)
return q2dest
q2dest = queue.Queue()
reversed_queue = reverseQueue(q1, q2dest)
while not reversed_queue.empty():
print(reversed_queue.get(), end=” “)
👉Output:
10 3 21 4 5 11
👉Summary
- Python Queue supports FIFO and LIFO principles.
- Use put() to add items and get() to remove them.
- FIFO ensures the first item added is the first one removed.
- LIFO ensures the last item added is the first one removed.
- Python queues are efficient for data handling in various applications.