Python Queues


A queue is another fundamental data structure that you will use often when working with ordered data. Unlike stacks, which follow the LIFO rule, queues follow FIFO, which means First In, First Out. The first item you add to the queue is the first item that comes out. This pattern appears in banking systems, customer support apps, printers, operating system tasks and many real-world situations where order matters.

In this tutorial, you will learn what a queue is, how it works, how to build queues using lists, how to use deque from the collections module and how the queue module helps with multi-threading. You will also explore real life uses, queue operations and practical examples to understand where queues fit in your Python programs.

What Is a Queue?

A queue is a linear data structure where items are added at one end and removed from the other. The two ends are:

  • Front – where items are removed

  • Rear – where items are added

Queues are helpful whenever you need to manage tasks in the order they arrive.

What is the FIFO Concept?

FIFO stands for First In, First Out. It is the core rule behind every queue.

Example:

  1. You enqueue 10

  2. You enqueue 20

  3. You enqueue 30

The queue looks like this (front → rear): 10, 20, 30

If you dequeue, you get 10 first because it entered first.

This makes queues perfect for handling tasks, requests or jobs in real-world order.

Creating a Queue Using Python Lists

You can create a basic queue using a Python list, but removing from the front is slow for large data.

Still, for beginners:

queue = []

queue.append(10)  # Enqueue
queue.append(20)
queue.append(30)

print(queue)

Removing the first item:

value = queue.pop(0)  # Dequeue
print(value)

This works but is not efficient for large programs.

Enqueue Operation

Enqueue adds an item to the rear.

queue.append(40)

This is used in banking queues, task lists and order processing systems.

Dequeue Operation

Dequeue removes from the front.

value = queue.pop(0)

This ensures tasks are processed in the order they arrive.

Using collections.deque for Better Performance

The best way to implement a queue in Python is by using deque.

from collections import deque

queue = deque()

queue.append(10)
queue.append(20)
queue.append(30)

print(queue.popleft())

popleft() removes the first element efficiently.

This is suitable for heavy applications and large queues.

Peek Operation

Peek means checking the first item without removing it.

queue[0]

This helps when you want to see what task is next.

Checking If a Queue Is Empty

A safe check prevents errors:

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

This is important in apps where tasks come from users or external systems.

Using the queue Module

Python has a built-in queue module that is used in multi-threading. It is designed for safe, synchronized communication between threads.

import queue

q = queue.Queue()

q.put(10)   # Enqueue
q.put(20)

print(q.get())   # Dequeue

Key methods:

  • put() – add item

  • get() – remove item

  • empty() – check if queue is empty

  • full() – check if queue is full

This is used in real applications where multiple threads need to send tasks to each other.

Implementing a Queue Class

You can create your own queue class for cleaner code.

class Queue:
    def __init__(self):
        self.items = []

    def enqueue(self, item):
        self.items.append(item)

    def dequeue(self):
        if not self.items:
            return None
        return self.items.pop(0)

    def peek(self):
        if not self.items:
            return None
        return self.items[0]

    def is_empty(self):
        return len(self.items) == 0

This class is useful in structured programs and DSA practice.

Real-Life Uses of Queues

Customer Service Systems

Requests are processed in the order they arrive.

Printer Tasks

Print jobs wait in a queue until the previous job completes.

Order Processing

Online orders, tickets or service calls use FIFO.

OS Task Scheduling

Operating systems use queues to manage processes and tasks.

Messaging Systems

Chat servers and notifications are processed in queue style.

These situations show why queues are essential for real-world programs.

Queue Simulation: Customer Service

from collections import deque

queue = deque()

queue.append("Riya")
queue.append("Aisha")
queue.append("Meera")

while queue:
    print("Serving:", queue.popleft())

This mirrors how customer tokens are handled.

Queue Simulation: Task Scheduler

tasks = deque(["task1", "task2", "task3"])

while tasks:
    current = tasks.popleft()
    print("Processing:", current)

Useful in apps that run background jobs.

Practical Examples

Example 1: Create a queue

queue = deque()

Example 2: Enqueue items

queue.append(10)

Example 3: Dequeue item

queue.popleft()

Example 4: Peek front item

queue[0]

Example 5: Check empty

len(queue) == 0

Example 6: Using queue module

import queue
q = queue.Queue()

Example 7: Enqueue with put()

q.put(50)

Example 8: Dequeue with get()

q.get()

Example 9: Limited size queue

q = queue.Queue(maxsize=5)

Example 10: Queue class usage

q = Queue()
q.enqueue(100)

Summary of the Tutorial

A queue is a FIFO structure used everywhere in computing. You learned how queues add items at the rear and remove from the front, how to build queues using lists, how to use deque for performance and how the queue module supports multi-threading. Queues power customer service apps, printer systems, order management, OS schedulers and messaging systems. Once you understand queues, you can apply them to many real-world programs and larger DSA structures like graphs, trees and network processing.


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.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top