Python List as Queues
Python Queues Implementation
In computer science, queues are data structures that operate on afirst-in, first-out (FIFO) logic. This means a new element is added to index 0 and an element is removed from index 0 only.
Queue Related Functions
Instead of enqueue()
use append()
method, instead of dequeue()
use pop(0)
method for removing the first element. pop(0)
method also returns the removed item. Example code:
queue= [1, 2, 3]
queue.append(4)
queue.append(5)
print("Queue after append operations:", stack)
queue.pop(0)
queue.pop(0)
print("\nRemoved item": queue.pop(0))
print("\nQueue after pop operations:", queue)
Queue after append operations: [1, 2, 3, 4, 5]
Removed item: 3
Queue after pop operations: [4, 5]
Implementation Using collections.deque
Python’s built-in collections.deque
class is also a preferred way to implement queues. Deque is preferred more in cases where we need more efficient append and pop operations, just like lists. Deque provides an O(1) time complexity for append
and popleft
operations where lists have an O(n) time complexity.
Note: popleft
is same as pop(0)
.
from collections import deque
# Create an empty queue
queue = deque()
# Push elements onto the queue using append
queue.append(10)
queue.append(20)
queue.append(30)
# Print the queue
print("Queue:", queue)
# Pop elements from the queueusing pop
popped_element = queue.popleft()
print("Popped Element:", popped_element)
# Print the updated queue
print("Updated Queue:", queue)
Queue: deque([10, 20, 30])
Popped Element: 10
Updated Stack: deque([20, 30])