Python implements queues using lists, collections.deque
for efficient operations, and the queue
module for thread-safe FIFO queues.
Key takeaways:
A queue is a linear data structure that processes elements in the order they are added, following the First-In/First-Out (FIFO) method. The primary operations are enqueue (adding an element), dequeue (removing an element), front (accessing the first element), and rear (accessing the last element).
Queues in Python can be implemented using lists (with
append()
andpop(0)
), theQueue
module (using methods likeput()
,get()
, andempty()
), or thecollections.deque
module (usingappend()
andpopleft()
for efficient operations).While lists offer simplicity,
deque
provides efficient operations, and theQueue
module adds thread safety, making it suitable for concurrent programming scenarios.
Queue is a linear data structure that stores items in a First-In/First Out (FIFO) manner. In the queue, the data element that is inserted first will be removed first.
Operations that can be performed on the queue are:
Enqueue
: It adds an item to the queue. If the queue is full, then it is said to be an overflow condition.
Dequeue
: It removes an item from the queue. The items are popped in the same order in which they are pushed. If the queue is empty, then it is said to be an Underflow condition.
Front
: It gives the front item from the queue.
Rear
: It gives the last item from the queue.
Note: The time complexity for all of the above operations is
.
In a queue, “peek” refers to the operation of viewing the element at the front of the queue without removing it. This allows you to check the first element without modifying the queue.
When working with a queue in Python, you typically don’t have a direct peek()
method (as you might in other data structures). However, you can access the front element by using indexing.
If you want to peek at the front of the queue, you can use the index 0
.
The -1
index refers to accessing the last element in the queue. In Python, negative indexes start from the end of the list. So:
queue[-1]
will return the last element in the queue (the rightmost side in a deque).
So, to summarize:
queue[0]
: Peeks at the front of the queue (first element).
queue[-1]
: Peeks at the back of the queue (last element).
Queue in Python can be implemented in the following ways:
Using Python lists
Using Queue
module
Using the collections.deque
module
In Python lists, we can use the append()
method to add elements to the end of the list, effectively simulating the enqueue operation and the pop()
method to remove elements from the beginning with an index of 0, effectively simulating the dequeue operation easily.
# implementing Queue using List :q=[]q.append(10)q.append(100)q.append(1000)q.append(10000)print("Initial Queue is:",q)print(q.pop(0))print(q.pop(0))print(q.pop(0))print("After Removing elements:",q)def is_empty():return len(q) == 0def size():return len(q)print("Check queue is empty or not", is_empty())print("Size of the queue:", size())
Queue
moduleThe Queue
module in Python provides a convenient and thread-safe way to implement a FIFO (First-In-First-Out) queue. We have used the following methods to implement the queue:
put()
: It inserts the specified element into the queue.
get()
: It removes and returns the element at the front of the queue.
empty()
: It returns True
if the queue is empty; otherwise, it returns False
.
qsize()
: It returns the size of the queue.
# implment queue using queue modulefrom queue import Queueq=Queue(maxsize=4)print("Initial Size Before Insertion:",q.qsize())q.put('A')q.put('AA')q.put('AAA')q.put('AAAA')print("After Insertion:",q.qsize())print("Queue is Full or Not:",q.full())print("Size of Queue:",q.qsize())print("Removing Elements:")print(q.get())print(q.get())print(q.get())print("Empty or Not??",q.empty())print(q.get())print("Empty or Not??",q.empty())print("Size of Queue:",q.qsize())
collections.deque
moduleThe collections.deque
module in Python provides a double-ended queue (deque) that allows adding and removing elements efficiently from both ends. The following methods we have used to implement queue:
append()
: It inserts the specified element into the queue.
popleft()
: It removes and returns the element at the front of the queue.
To get elements from the other side of the deque (the right end), you can use the pop()
method, which removes and returns the element at the end of the queue.
from collections import dequeq=deque()q.append(10)q.append(100)q.append(1000)q.append(10000)print("Initial Queue is:",q)print(q.popleft())print(q.popleft())print("After Removing elements:",q)
Learn the basics with our engaging course!
Start your coding journey with our “Learn Python” course, the perfect course for absolute beginners! Whether you’re exploring coding as a hobby or building a foundation for a tech career, this course is your gateway to mastering Python—the most beginner-friendly and in-demand programming language. With simple explanations, interactive exercises, and real-world examples, you’ll confidently write your first programs and understand Python essentials. Our step-by-step approach ensures you grasp core concepts while having fun along the way. Join now and start your Python journey today—no prior experience is required!
Queues are fundamental data structures that adhere to the First-In/First-Out (FIFO) principle, making them essential for various real-world applications like scheduling and buffering. Python offers multiple ways to implement queues, each suited to specific needs: lists for simplicity, the Queue
module for thread-safe operations in concurrent programming, and the collections.deque
module for efficient enqueue and dequeue operations. Understanding these implementations allows developers to choose the most suitable approach for their projects, ensuring efficiency and clarity in handling sequential data.
Haven’t found what you were looking for? Contact Us