What is a queue?
- Algorithms course
- Beginner
- Lesson 65/80
- 4 min
A FIFO (first in first out) data structure.
What is a queue?
A queue works on the first-in-first-out (FIFO) principle. Elements are added at the back and removed from the front.
Adding to a queue is called enqueue, removing is dequeue. Think of it like lining up and being served.
Enqueue and dequeue
enqueue(item) adds an element to the back of the queue. dequeue() removes and returns the front element.
Enqueue is O(1). Dequeue can be O(1) or O(n) depending on implementation. Popping from the front of a list is O(n), a circular queue is O(1).
Practice Enqueue
Write queue_enqueue(queue, item). Add to back, return queue. Print [5] with print(queue_enqueue([], 5)).
Starter code
def queue_enqueue(queue, item):
# EnqueueSample solution
def queue_enqueue(queue, item):
# Enqueue
queue.append(item)
return queue
print(queue_enqueue([], 5))Expected output
[5]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which principle does a queue follow?
- Random
- FIFO
- Sorted
- LIFO Correct answer
Explanation: Queue follows FIFO.
2 Enqueue
Adding to a queue is called ____.
Adding to a queue is called enqueue.
Explanation: enqueue is right.
3 What is a queue: match the terms
| Term | Meaning |
|---|---|
enqueue |
Add to back |
dequeue |
Remove from front |
FIFO |
First in first out |
front |
Front |