Table of contents
1.
Introduction
2.
Queue in Python
3.
What is the Queue?
4.
Operations in Python
5.
Methods Available in Queue
6.
The Built-in Python List
7.
Adding Element to a Queue (Enqueue)
8.
Removing Element from a Queue (Dequeue)
9.
Sorting the Queue
10.
The Queue Module
11.
Working With queue.Queue Class
12.
Working With collection.deque Class
13.
The multiprocessing.Queue Class
14.
Priority Queue in Python
14.1.
Manually Sorted List
15.
The queue.PriorityQueue Class
16.
Frequently Asked Questions
16.1.
What is a queue in Python? 
16.2.
Which module provides thread-safe queues in Python?
16.3.
How do you implement a priority queue in Python? 
17.
Conclusion
Last Updated: Dec 30, 2024
Medium

Queue in Python

Author Sinki Kumari
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Python queues are essential for managing data in a sequential order. Whether you are developing a chatbot, managing tasks, or handling real-time data, queues help store and process items efficiently. 

Queue in Python

In this article, we will discuss queues in Python, their types, operations, and methods with practical examples. 

Queue in Python

In Python, a queue is a linear data structure that follows the First In First Out (FIFO) principle. It means that the first element inserted into the queue will be the first one to be removed. Queues are useful in various scenarios, such as task scheduling, resource management, and event handling.

Python provides several ways to implement queues, like:

1. Using a list

2. Using collections.deque

3. Using queue.Queue

What is the Queue?

In simple terms, a queue is a collection of elements that supports two main operations:

  1. Enqueue: Adding elements to the queue.
     
  2. Dequeue: Removing elements from the queue.

Queues ensure orderly processing of data, making them ideal for situations requiring sequential operations.

Operations in Python

Queues support the following operations:

  1. Enqueue: Add an element to the back of the queue.
     
  2. Dequeue: Remove an element from the front of the queue.
     
  3. Peek: View the front element without removing it.
     
  4. Check Empty: Determine if the queue is empty.

Methods Available in Queue

Depending on the implementation, Python queues offer methods like:

  1. put(item): Adds an item to the queue.
     
  2. get(): Removes an item from the queue.
     
  3. qsize(): Returns the number of items in the queue.
     
  4. empty(): Checks if the queue is empty.
     
  5. full(): Checks if the queue is full (for bounded queues).

The Built-in Python List

Python's built-in list data structure can be used to implement a queue. To achieve the FIFO behavior, we can use the `append()` method to add elements to the end of the list & the `pop(0)` method to remove elements from the beginning of the list.


For example: 


1: Creating a queue using a list

queue = []


2: Adding elements to the queue

queue.append(1)
queue.append(2)
queue.append(3)
print("Queue:", queue) 
You can also try this code with Online Python Compiler
Run Code


Output: 

Queue: 
[1, 2, 3]


3: Removing elements from the queue

element = queue.pop(0)
print("Removed element:", element)  
You can also try this code with Online Python Compiler
Run Code


Output: 

Removed element: 1
print("Queue after removal:", queue)  
You can also try this code with Online Python Compiler
Run Code


Output: 

Queue after removal: [2, 3]


In this example, we create an empty list called `queue`. We then use the `append()` method to add elements to the end of the list, simulating the enqueue operation. To remove an element from the queue, we use the `pop(0)` method, which removes & returns the first element of the list.

Even though using a list as a queue is simple and easy, it has some limitations, too. Removing elements from the beginning of a list using `pop(0)` has a time complexity of O(n) because all the subsequent elements need to be shifted one position to the left. For larger queues, this can be inefficient.

Explanation for the examples:

Let's understand the example step by step and see a proper explanation of each part.


1: Creating a queue using a list

queue = []


In this line, we create an empty list called `queue` to represent our queue. Lists in Python are dynamic arrays that can store elements of different data types.


2: Adding elements to the queue

queue.append(1)
queue.append(2)
queue.append(3)


We use the `append()` method to add elements to the end of the `queue` list. In this example, we add the elements `1`, `2`, and `3` to the queue. After these operations, the `queue` list will contain `[1, 2, 3]`.

print("Queue:", queue)  
You can also try this code with Online Python Compiler
Run Code


Output: 

Queue: [1, 2, 3]


We print the current state of the `queue` list using the `print()` function. The output will be `Queue: [1, 2, 3]`, showing the elements in the order they were added.

3: Removing elements from the queue

element = queue.pop(0)
print("Removed element:", element)  
You can also try this code with Online Python Compiler
Run Code


Output: 

Removed element: 1


To remove an element from the queue, we use the `pop()` method with an index of `0`. This removes and returns the first element of the list, which is `1` in this case. We store the removed element in the `element` variable and print it.

print("Queue after removal:", queue)  
You can also try this code with Online Python Compiler
Run Code


Output:

Queue after removal: [2, 3]


Finally, we print the state of the `queue` list after removing an element. The output will be `Queue after removal: [2, 3]`, showing that the first element `1` has been removed, and the remaining elements have been shifted to the left.

Note: This example shows the basic operations of adding and removing elements from a queue using a Python list. However, as mentioned earlier, using `pop(0)` to remove elements from the beginning of a list can be inefficient for large queues due to the time complexity of shifting elements.


Example:

queue = []
# Enqueue
queue.append(1)
queue.append(2)
queue.append(3)
print("Queue after enqueue:", queue)

# Dequeue
removed = queue.pop(0)
print("Removed element:", removed)
print("Queue after dequeue:", queue)
You can also try this code with Online Python Compiler
Run Code


Output:

Queue after enqueue: [1, 2, 3]
Removed element: 1
Queue after dequeue: [2, 3]

Adding Element to a Queue (Enqueue)

To add an element to a queue:

  • Use append() for lists.
     
  • Use put() for queues.
     

Example:

from queue import Queue
q = Queue()
q.put(10)
q.put(20)
print("Queue size after enqueue:", q.qsize())
You can also try this code with Online Python Compiler
Run Code


Output:

Queue size after enqueue: 2

Removing Element from a Queue (Dequeue)

To remove an element from a queue:

  • Use pop(0) for lists.
     
  • Use get() for queues.
     

Example:

from queue import Queue
q = Queue()
q.put(10)
q.put(20)
removed = q.get()
print("Removed element:", removed)
print("Queue size after dequeue:", q.qsize())
You can also try this code with Online Python Compiler
Run Code

Output:

Removed element: 10
Queue size after dequeue: 1

Sorting the Queue

Sorting can be done manually or using specific methods. For lists, you can use sort().

Example:

queue = [3, 1, 2]
queue.sort()
print("Sorted queue:", queue)
You can also try this code with Online Python Compiler
Run Code


Output:

Sorted queue: [1, 2, 3]

The Queue Module

The queue module in Python provides a robust way to implement queues. It includes:

  1. queue.Queue: Thread-safe FIFO queue.
     
  2. queue.LifoQueue: Last In, First Out (LIFO) queue.
     
  3. queue.PriorityQueue: Priority-based queue.

Working With queue.Queue Class

The queue.Queue class provides thread-safe FIFO queues.

Example:

from queue import Queue


q = Queue()
q.put("A")
q.put("B")
print(q.get())
print(q.get())
You can also try this code with Online Python Compiler
Run Code


Output:

A
B

Working With collection.deque Class

The collections.deque class offers a highly optimized way to implement queues. It supports:

  1. Adding elements to either end.
     
  2. Removing elements from either end.
     

Example:

from collections import deque
queue = deque()
queue.append(1)  # Enqueue
queue.append(2)
print("Dequeued element:", queue.popleft())
print("Current queue:", queue)
You can also try this code with Online Python Compiler
Run Code


Output:

Dequeued element: 1
Current queue: deque([2])

The multiprocessing.Queue Class

The multiprocessing.Queue class is used for inter-process communication.

Example:

from multiprocessing import Queue


q = Queue()
q.put("Task 1")
q.put("Task 2")


print("Dequeued:", q.get())
You can also try this code with Online Python Compiler
Run Code


Output:

Dequeued: Task 1

Priority Queue in Python

A priority queue processes elements based on their priority.

Manually Sorted List

You can use a list and sort it based on priority.

Example:

queue = [(2, "B"), (1, "A"), (3, "C")]
queue.sort()
print("Sorted priority queue:", queue)
You can also try this code with Online Python Compiler
Run Code


Output:

Sorted priority queue: [(1, 'A'), (2, 'B'), (3, 'C')]

The queue.PriorityQueue Class

This class automatically manages elements based on priority.

Example:

from queue import PriorityQueue
pq = PriorityQueue()
pq.put((1, "A"))
pq.put((3, "C"))
pq.put((2, "B"))
while not pq.empty():
    print(pq.get())
You can also try this code with Online Python Compiler
Run Code


Output:

(1, 'A')
(2, 'B')
(3, 'C')

Frequently Asked Questions

What is a queue in Python? 

A queue is a data structure that follows FIFO, where elements are added at one end and removed from the other.

Which module provides thread-safe queues in Python?

 The queue module provides thread-safe queues such as queue.Queue, queue.LifoQueue, and queue.PriorityQueue.

How do you implement a priority queue in Python? 

A priority queue can be implemented using the queue.PriorityQueue class or by manually sorting a list based on priority.

Conclusion

Queues in Python provide a systematic way to handle data. They can be implemented using lists, the queue module, collections.deque, or multiprocessing.Queue. Each method has its advantages depending on the use case. By understanding these concepts and implementations, you can efficiently solve real-world problems.

You can also check out our other blogs on Code360.

Live masterclass