What is the Queue?
In simple terms, a queue is a collection of elements that supports two main operations:
- Enqueue: Adding elements to the queue.
- 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:
- Enqueue: Add an element to the back of the queue.
- Dequeue: Remove an element from the front of the queue.
- Peek: View the front element without removing it.
- Check Empty: Determine if the queue is empty.
Methods Available in Queue
Depending on the implementation, Python queues offer methods like:
- put(item): Adds an item to the queue.
- get(): Removes an item from the queue.
- qsize(): Returns the number of items in the queue.
- empty(): Checks if the queue is empty.
- 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 CodeOutput:
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:
- queue.Queue: Thread-safe FIFO queue.
- queue.LifoQueue: Last In, First Out (LIFO) queue.
- 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:
- Adding elements to either end.
- 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.