Python Queues


Queue is a linear data structure that follows the FIFO (First In, First Out)** principle — the first element added is the first one to be removed.

Python doesn’t have a built-in queue type, but you can implement queues using:

  • List

  • collections.deque (recommended)

  • queue.Queue (for multithreading)


🔹 Queue Using List (Basic)

queue = []

# Enqueue
queue.append('a')
queue.append('b')
queue.append('c')

print(queue)  # ['a', 'b', 'c']

# Dequeue
queue.pop(0)  # Removes 'a'
print(queue)  # ['b', 'c']

❗ Lists are not ideal for queues as removing from the front is slow for large data.


🔹 Queue Using collections.deque (Recommended)

from collections import deque

queue = deque()

queue.append('apple')     # Enqueue
queue.append('banana')
queue.append('cherry')

print(queue.popleft())    # Dequeue → apple
print(queue)              # deque(['banana', 'cherry'])

deque is fast and efficient for queue operations.


🔹 Peek Front and Rear

print("Front:", queue[0])
print("Rear:", queue[-1])

🔹 Check If Queue is Empty

if not queue:
    print("Queue is empty")
else:
    print("Queue is not empty")

🔹 Use Case Examples

  • Print queues

  • Customer service systems

  • Task scheduling

  • Breadth-first search in trees/graphs


Practice Questions

Q1. Write a Python program to create a queue and add 5 names to it.

Q2. Write a Python program to remove 2 elements from the queue using popleft() from collections.deque.

Q3. Write a Python program to print the first and last item in the queue.

Q4. Write a Python program to implement a queue using a list (with append() and pop(0)).

Q5. Write a Python program to check if the queue is empty before removing an item.

Q6. Write a Python program to enqueue items in order: A, B, C — then dequeue one and print the result.

Q7. Write a Python program to use len() to print the current size of the queue.

Q8. Write a Python program to clear all elements from the queue.

Q9. Write a Python program to create a number queue and calculate the sum of all items.

Q10. Write a Python program to simulate a ticket booking queue where users are served in the order they arrive.


Go Back Top