Queue Using Array in Python
A Queue is one of the common linear data structures obeying the FIFO (First In, First Out) rule. Similar to a ticket counter queue in real life, the first inserted item will be deleted first.
Get Chirag Chandel’s stories in your inbox
Join Medium for free to get updates from this writer.
While we typically implement queues with collections.deque or using the queue module in Python, it is useful to learn how to implement a queue with arrays (Python lists) so that we can better grasp its basic working.
Key Properties of Queue
- FIFO Order → First element inserted is the first to be removed.
- Two main operations:
- Enqueue → Insert element at the rear.
- Dequeue → Remove element from the front
3. Overflow & Underflow Conditions:
- Overflow → Queue is full and cannot accept new elements.
- Underflow → Queue is empty, and we try to remove an element.
Queue Operations Using Array (List in Python)
Let’s implement a Queue class step by step.
class Queue:
def __init__(self, capacity):
self.queue = []
self.capacity = capacity
# Enqueue operation
def enqueue(self, item):
if len(self.queue) == self.capacity:
print("Queue Overflow! Cannot insert", item)
else:
self.queue.append(item)
print(f"Enqueued: {item}")
# Dequeue operation
def dequeue(self):
if len(self.queue) == 0:
print("Queue Underflow! No elements to remove.")
else:
removed = self.queue.pop(0) # Removes front element
print(f"Dequeued: {removed}")
# Peek operation (get front element)
def peek(self):
if len(self.queue) == 0:
print("Queue is empty")
else:
print("Front Element:", self.queue[0])
# Display queue
def display(self):
print("Current Queue:", self.queue)Example Usage
# Create a queue of size 5
q = Queue(5)q.enqueue(10)
q.enqueue(20)
q.enqueue(30)
q.display()q.dequeue()
q.display()q.peek()
Output
Enqueued: 10
Enqueued: 20
Enqueued: 30
Current Queue: [10, 20, 30]
Dequeued: 10
Current Queue: [20, 30]
Front Element: 20Limitations of Queue Using Array
- Shifting Problem → When we
dequeue, elements shift left (pop(0)), which takes O(n) time. - Fixed Size → Queue has limited capacity when implemented with arrays.
- Inefficient for Large Data → Not suitable for high-performance systems.
Alternative Implementations
- Circular Queue → Avoids shifting problem by connecting end to front.
- Linked List Based Queue → Dynamic size without overflow (until memory is available).
- Python’s
dequeModule → Provides highly optimized queue operations.
mplementing a queue using arrays in Python is a great way to understand its core operations and limitations. Once you master this, you can easily extend the concept to circular queues, priority queues, and deque structures.









