Enqueue and dequeue
- Algorithms course
- Beginner
- Lesson 66/80
- 4 min
enqueue to the back, dequeue from the front.
Dequeue operation
dequeue() removes and returns the front element of the queue. This is the first element that was added.
Dequeuing an empty queue is an error. Therefore, check emptiness first. An empty queue may return None or raise an error.
Front and back
The queue's front is the first element added, the back is the last. Enqueue goes to back, dequeue comes from front.
Think of it like a waiting line: the first to arrive is served first. This is fair queue logic.
Practice Dequeue
Write queue_dequeue(queue). Remove and return the front element. Print 5 with print(queue_dequeue([5, 10, 15])).
Starter code
def queue_dequeue(queue):
# DequeueSample solution
def queue_dequeue(queue):
# Dequeue
return queue.pop(0)
print(queue_dequeue([5, 10, 15]))Expected output
5
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Dequeue
Removing from a queue is done with ____.
Removing from a queue is done with dequeue.
Explanation: dequeue is right.
2 Enqueue and dequeue: match the terms
| Term | Meaning |
|---|---|
dequeue |
Remove from front |
front |
First element |
back |
Last element |
FIFO |
First in first out |
3 Which element does dequeue remove?
- A random one
- The front one Correct answer
- The back one
- The largest
Explanation: It removes the front element.