Python deque.popleft and IndexError
An empty deque raises IndexError when the receptionist removes its first ticket.
A simple example
deque.popleft and IndexError
- Start with Queue containing no items
- Do this Request the first item
- Result No item available
Syntax
queue.popleft()
Run these examples in Python
Save one example at a time as lesson.py. Use Python 3.9 or later.
python3 lesson.pyCall the next person at the clinic
A receptionist calls patients from the morning queue. If the final patient has already checked in, the screen should display an empty-queue message instead of trying to issue another number.
from collections import deque
patients = deque()
try:
print(patients.popleft())
except IndexError:
print("No patients waiting")
No patients waiting
The queue has no patient at its front. The screen reports the empty state to the receptionist.
Call a waiting pupil
The music desk has one pupil in its equipment queue. Take the next name from the queue. An empty queue should send the desk back to waiting.
Check an empty ticket queue
The counter opens before anyone has taken a ticket. Take the next name from the queue. An empty queue should send the desk back to waiting.
What to watch for
Handle the exception around removal so an unrelated indexing problem stays visible.