Sub topic 1
What a Queue Is: FIFO and Its Operations
Prerequisites
This chapter assumes you know basic Python syntax, functions, and classes. You should be comfortable with lists and indexing, and with Big-O notation for common operations such as O(1) and O(n). Later chapters also use dictionaries and sets, but this one does not.
The queue idea
A queue is a collection that returns items in the same order they were added. The first item in is the first item out. This rule is called FIFO, short for first in, first out.
A line at a ticket counter works this way. New people join at the back, and the person at the front is served first. Nobody can skip ahead, and nobody leaves from the middle.
A queue is an abstract data type (ADT). An ADT defines what operations exist and how they behave. It does not say how the data is stored. A list, a chain of linked nodes, or a fixed array can all implement a queue. The next chapters compare those choices.
The core operations
Every queue offers a small set of operations.
| Operation | Meaning | Changes the queue? |
|---|---|---|
| enqueue(item) | Add an item at the back | Yes |
| dequeue() | Remove and return the item at the front | Yes |
| peek() | Return the front item without removing it | No |
| size() | Return the number of items | No |
Many libraries also provide an is_empty check. In Python it is usually written as len(q) == 0 or not q.
The two ends have different roles. Items enter at the back, which is also called the tail. Items leave from the front, which is also called the head. The diagram shows one item entering and another leaving.
Behavior on a worked example
Suppose the queue starts empty. You enqueue "a", "b", and "c" in that order. The front is now "a". A dequeue returns "a", then the next dequeue returns "b". Order is preserved: the output order matches the input order.
Here is a small class that wraps a Python list and exposes the four operations. It is a first draft. It is correct, but it is not efficient, and the next chapter explains why.
class ListQueue:
def __init__(self):
self._items = []
def enqueue(self, item):
self._items.append(item)
def dequeue(self):
if not self._items:
raise IndexError("dequeue from empty queue")
return self._items.pop(0)
def peek(self):
if not self._items:
raise IndexError("peek from empty queue")
return self._items[0]
def size(self):
return len(self._items)
q = ListQueue()
for letter in ["a", "b", "c"]:
q.enqueue(letter)
print(q.peek()) # a
print(q.dequeue()) # a
print(q.dequeue()) # b
print(q.size()) # 1Notice that peek and dequeue both return "a" the first time. The difference is that peek leaves the item in place, so size is unchanged after it.
Empty and full queues
Two edge cases need a decision from whoever designs the queue.
- Dequeue or peek on an empty queue. There is no item to return. A queue can raise an exception, as above, or return a marker such as
None. Raising is safer whenNonecould also be a valid item. - Enqueue on a full queue. An unbounded queue never fills up. A bounded queue has a fixed capacity, and it must raise an error, block, or discard something. Later chapters show all three behaviors.
Common errors
- Reversing the ends. Adding at the front and removing from the back gives a stack (last in, first out), not a queue. Check which end each operation touches.
- Peeking when you meant to dequeue.
peeknever shortens the queue, so a loop that only peeks will not finish. - Assuming a Python list is a good queue. It behaves correctly, but
pop(0)shifts every remaining element. That cost is the subject of the next chapter. - Treating the middle as accessible. A queue promises only front removal and back insertion. If you need to search or remove from the middle, a queue is the wrong tool.
Exercise
You enqueue 5, 8, 2, then call dequeue once, enqueue 9, and call peek. What does peek return, and what is the queue's size?
Show answer
peek returns 8 and the size is 3. The first dequeue removes 5, leaving 8 and 2. Enqueuing 9 puts it at the back, giving 8, 2, 9. The front is 8, and peek does not remove it.
Exercise
A teammate's queue adds new items at index 0 of a list and removes with pop() from the end. Is it FIFO? Explain.
Show answer
Yes. The newest item sits at index 0, and pop() removes the item at the end, which is the oldest one. Items leave in the order they arrived. It is still a valid FIFO queue, although inserting at index 0 shifts every element, so it is slow for large lists.