Module 5 · Stacks, Queues and Linked Lists · Lesson 16 of 40

Queues and deques: first in, first out

A line where you join at the back and leave from the front. Use collections.deque in Python.

In this lesson · about 18 minutes

  • Explain FIFO and where queues are used
  • Use collections.deque for a fast queue
  • Know what a circular queue and a deque are

A queue is a line at a shop. People join at the back and leave from the front. The first one in is the first one out: FIFO.

ActionMeaningPython dequeCost
enqueueJoin at the backq.append(x)O(1)
dequeueLeave from the frontq.popleft()O(1)
frontWho is next?q[0]O(1)

Why not a plain list?

list.pop(0) removes the front item, but then every other item slides left: O(n). The deque ("deck") from the collections module is built to add and remove at both ends in O(1).

from collections import deque
q = deque()
q.append("Ana")      # join
q.append("Ben")
q.popleft()          # "Ana" leaves first

Circular queue

A queue stored in a fixed-size array can "wrap around": when the back reaches the end of the array, it continues at index 0 if there is free space. This reuses space instead of wasting the boxes at the front. The trick is (index + 1) % size.

Deque: both ends

A deque (double-ended queue) can add and remove at both ends: append, appendleft, pop, popleft. It can act as a stack or a queue.

Where queues appear

  • Printer jobs, waiting lists, customer support tickets.
  • Breadth-first search in trees and graphs (coming later!).

Try it · see it work

Compare a stack and a queue

Add the same letters to both, then remove one from each. The stack gives back the newest; the queue gives back the oldest.

Stack (LIFO), like a pile of plates

AB ← top

Queue (FIFO), like a line at a shop

front →AB← back

Add the same items to both, then remove one from each. Which item leaves first?

Try it: a ticket queue

Exercise

Pass the parcel

Children sit in a circle and pass a parcel. Every time it has been passed k times, the child holding it leaves. Write last_child(names, k) that returns the name of the last child left. Use a deque: to "pass", move the front child to the back with q.append(q.popleft()).

Code that runs before yours
from collections import deque

Check your understanding0 of 3 correct

Question 1

1.Enqueue A, B, C, then dequeue. What comes out?

Question 2

2.Why use deque instead of list for a queue?

Question 3

3.Which can add and remove at both ends?

Quiz score: 0 of 3

Exercises solved: 0 of 1

Tip: answer every quiz question correctly first.

Noviq Academy is free and for learning. This course follows the topics of a set of DSA study notes, rewritten in Noviq's own words with Python examples. Python runs in your own browser with Pyodide; nothing you type is sent to Noviq.