Queues: First In, First Out, With a Ring of Cells
A queue is first in, first out: whoever joins the line first is served first. Build Kate's cinema ticket line in Python as a ring of four cells, where nobody steps forward and only head and tail move, serve a million people with the same four cells, then break it with a line that is already full.
What you will learn
- Explain first in, first out with a cinema ticket line
- Build a circular-array queue in Python with head, tail and count
- Explain why enqueue and dequeue are O(1) when nobody moves
- Spot and guard against the full-queue bug
Before you start
- Python classes and lists
- Stacks
A queue is first in, first out: whoever joins the line first is served first. It's the opposite of a stack, and the trick that makes it fast is that nobody ever walks.
The ticket line
Kate runs a small cinema app. For the Friday show, Emma asks for a ticket first, then Jack, then Tom. The app must be fair: the first ticket goes to Emma, the second to Jack. First come, first served.
Picture the line at the cinema desk. A new person always joins at the back. When the desk is free, the person at the front is served. And if Max walks in and stands right at the front, that's cutting in, and it isn't fair.
There are three words for this. Enqueue means join at the back. Dequeue means leave from the front. Peek means look at who's at the front. First in, first out is FIFO for short.
Nobody walks
Inside the program, the line is a row of cells, one person per cell. So when Emma leaves, what do you do?
Way one: everyone steps forward. Jack moves into her cell, Tom into his. With a million people waiting, that's a million moves for one ticket.
Way two: nobody moves. A number called head says where the front is. Emma leaves, and head simply becomes 1. One step, however long the line is. But the row has an end, so after the last cell you wrap round to cell 0, like a ring. In code that's (tail + 1) % len(line). This is called a circular array.
Inside TicketQueue
class TicketQueue:
def __init__(self, capacity):
self.line = [None] * capacity
self.head = 0 # the front: served next
self.tail = 0 # the back: next free cell
self.count = 0
def enqueue(self, name):
self.line[self.tail] = name
self.tail = (self.tail + 1) % len(self.line) # wrap to 0
self.count += 1
def dequeue(self):
name = self.line[self.head]
self.line[self.head] = None
self.head = (self.head + 1) % len(self.line)
self.count -= 1
return name
def peek(self):
return self.line[self.head]
def size(self):
return self.count
line is the row of cells, head is the front, tail is the next free cell, and count counts the people. enqueue puts the name in line[tail], moves tail on with the wrap, and adds one to count. dequeue reads the name at head, clears that cell, moves head on, and takes one off count. No loop anywhere, and nobody is moved.
The ticket line in code
from ticket_queue import TicketQueue
line = TicketQueue(4)
line.enqueue("Emma")
line.enqueue("Jack")
line.enqueue("Tom")
print("Front: " + line.peek())
print("Ticket for " + line.dequeue())
print("Ticket for " + line.dequeue())
line.enqueue("Kate")
line.enqueue("Liam") # goes into cell 0
print("Front: " + line.peek())
print("Waiting: " + str(line.size()))
Front: Emma
Ticket for Emma
Ticket for Jack
Front: Tom
Waiting: 3
Play it. Four empty cells, head and tail both at 0. Emma goes into cell 0 and tail moves to 1. Jack goes into cell 1, Tom into cell 2, and tail is 3. Peek reads cell 0: Emma. Dequeue serves Emma and head moves to 1; dequeue again serves Jack and head is 2. Kate goes into cell 3, the last cell, and (3 + 1) % 4 is 0, so tail wraps round. Liam goes into cell 0, the cell Emma left. Peek shows Tom, and three people are waiting.
A million people
from ticket_queue import TicketQueue
for n in (100, 10_000, 1_000_000):
line = TicketQueue(4)
last = ""
for i in range(1, n + 1):
line.enqueue("person " + str(i))
last = line.dequeue()
print(f"{n:9,d} people, 4 cells, last ticket: {last}")
100 people, 4 cells, last ticket: person 100
10,000 people, 4 cells, last ticket: person 10000
1,000,000 people, 4 cells, last ticket: person 1000000
A million people go through the same four cells, used again and again. Had everyone stepped forward instead, a line of a million would cost 999,999 moves for one ticket, and nearly five hundred billion moves to serve them all. With the markers, it's one step per ticket.
The line is full
Now break it. Only two cells, but three people join:
from ticket_queue import TicketQueue
line = TicketQueue(2)
line.enqueue("Emma")
line.enqueue("Jack")
line.enqueue("Tom") # the line is already full
print("Waiting: " + str(line.size()))
print("Ticket for " + line.dequeue())
Waiting: 3
Ticket for Tom
After Jack, tail wraps to cell 0. Nobody asked whether the line was full, so Tom writes over Emma. The count still says three, and the first ticket goes to Tom, not Emma. No crash and no warning, just a wrong answer. That's worse than a crash, because nothing tells you. A real queue checks whether count == len(line) before it lets someone join.
One step, however long the line
| Operation | Cost | Watch out |
|---|---|---|
| enqueue | O(1) | check the line isn't full first |
| dequeue | O(1) | check it isn't empty |
| peek | O(1) | |
| size | O(1) | |
| dequeue by shifting everyone forward | O(n) | the slow way to avoid |
In everyday Python, collections.deque gives you append and popleft in O(1), so it works as a queue out of the box. Avoid list.pop(0) for a long line: that's the everyone-steps-forward way.
Where you meet a queue
A printer prints documents in the order they were sent. A chat app delivers your messages in the order you sent them. A busy website answers visitors in the order they arrived, and a support line answers whoever has waited longest. For long jobs in a web app, a task queue does the same thing between programs.
Recap
- A queue is first in, first out: join at the back, leave from the front.
- Head and tail step along and wrap round a ring of cells, so every operation is one step.
- Guard a full line, or someone waiting gets written over.
Try it yourself: add an is_full method to TicketQueue, and make enqueue print "the line is full" instead of writing over someone.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related courses on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Data Structures and Algorithms Concepts: No Coding Needed
How stacks, trees, hash tables, sorting and graphs really work, step by step, with pictures.View on Udemy ↗: Data Structures and Algorithms Concepts: No Coding Needed (paid course, opens in a new tab)Related posts
What a Data Structure Is, and How Memory Works
Memory is a long row of numbered boxes, and opening any box is equally quick. A data structure is an agreed way of arranging things in those boxes, plus a few small notes. See with six songs on a phone why every structure is quick at some things and slow at others.
Arrays and Dynamic Arrays: Full? Get a Box Twice the Size
A fixed array never gets longer. A dynamic array fills its box, then copies everything into a box twice the size. Build one for Emma's playlist in Python, count the copies and shifts, and see why adding at the end stays cheap while inserting at the front costs almost 50 million shifts for 10,000 songs.
Linked Lists: A Chain of Clues, Built in Python
In a linked list every node holds a value and the address of the next node. Build a treasure hunt chain in Python: a new first clue is two moves at any size, slipping a clue in or out is just changing next, but reaching clue number i is a walk of i hops.
Stacks: Last In, First Out, With the Undo Button
A stack is last in, first out: the newest thing you put on is the first thing you take off. Build Emma's undo button in Python from a list and one top index, push, pop and peek in one step each, undo after a million edits, and see what happens when you pop an empty stack.
