Q.How can you avoid printing of None, when trying to print an empty queue?
You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.
Start your 14-day free trial to unlock the full solution →Return an explicit message string instead of None when the queue is empty, so the dequeue operation prints something meaningful rather than the default None value.
When you implement a queue using a Python list and write a dequeue() method, the natural instinct is to check if the queue is empty and simply return without a value. But here's the problem: a bare return statement in Python implicitly returns None. So when you write print(q.dequeue()) on an empty queue, you see None printed to the console — not very user-friendly.
The issue arises because Python functions that don't explicitly return a value evaluate to None. If your dequeue method looks like this:
def dequeue(self):
if len(self.queue) == 0:
return # implicit None
return self.queue.pop(0)
then calling print(q.dequeue()) on an empty queue prints None.
The solution: return a descriptive string
Instead of returning nothing (which becomes None), return an explicit message string that describes the underflow condition:
def dequeue(self):
if len(self.queue) == 0:
return "Queue is empty" # or "Underflow" or any message
return self.queue.pop(0)
Now when you print the result of dequeuing from an empty queue, you get a clear, readable message instead of None.
Complete example
class Queue:
def __init__(self):
self.queue = []
def enqueue(self, item):
self.queue.append(item)
def dequeue(self):
if len(self.queue) == 0:
return "Queue is empty"
return self.queue.pop(0)
def display(self):
print(self.queue)
# Usage
q = Queue()
print(q.dequeue()) # prints: Queue is empty
q.enqueue(10)
q.enqueue(20)
print(q.dequeue()) # prints: 10
print(q.dequeue()) # prints: 20
print(q.dequeue()) # prints: Queue is empty
Output:
Queue is empty
10
20 …
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.