Queues

First in, first out: people join at the back and are served from the front. A deque does both ends in O(1).

Python · intermediate · 4 min · 8 steps · free

What you'll learn

queue.py

from collections import deque

queue = deque()
queue.append('Ada')
queue.append('Linus')
queue.append('Grace')
served = queue.popleft()
queue.append('Alan')
print(served, list(queue))

Step by step

  1. deque (double-ended queue) comes from Python's collections module.
  2. queue is created and points to a new deque: [].
  3. 'Ada' is added to the end of the deque that queue points to.
  4. 'Linus' is added to the end of the deque that queue points to.
  5. Three people waiting, in arrival order.
  6. popleft serves the front of the queue: Ada, who came first.
  7. Alan joins at the back.
  8. It prints Ada ['Linus', 'Grace', 'Alan'].

Common mistakes

Best practices

Key takeaways

Check yourself

Queue or stack for a printer's jobs?

Answer: Queue. First come, first served.

list.pop(0) costs?

Answer: O(n)

·

More in Lists, Stacks, Queues and Hashing