SwadhyAI Notes

All Python notes

Python Queue 🚶

Queue Data Structure

Like stack, queue is a linear data structure that stores items in First In First Out (FIFO) manner. With a queue the least recently added item is removed first.

✨ Queue using List

List is a Python built-in data structure that can be used as a queue.

Instead of enqueue() and dequeue(), append() and pop() function is used.

However, lists are quite slow for this purpose. It is recommended to use the collections.deque class.

python
queue = []

# Adding elements to the queue
queue.append('a')
queue.append('b')
queue.append('c')

print("Initial queue")
print(queue)

# Removing elements from the queue
print("
Elements dequeued from queue")
print(queue.pop(0))
print(queue.pop(0))
print(queue.pop(0))

print("
Queue after removing elements")
print(queue)

🎮 Interactive Queue Demo

ℹ️ Ready to queue items!
FRONT
REAR
Person A0
Person B1
Person C2

⚡ Using collections.deque

Deque is preferred over list in the cases where we need quicker append and pop operations from both the ends of container.

python
from collections import deque

queue = deque(["Ram", "Tarun", "Asif", "John"])
print(queue)

queue.append("Akbar")
print(queue)

queue.append("Birbal")
print(queue)

print(queue.popleft())
print(queue.popleft())
print(queue)

✨ Pro Tip

Queues are used in Breadth First Search (BFS) and for handling requests in web servers.