Python 3D Academyবাংলা

First in, first out: queues and collections.deque

🌍 In real life. At the ticket counter at Kamalapur railway station, people stand in a line. Whoever came first is served first; anyone new joins at the back. Nobody pushes in at the middle, and nobody at the back is served before the people ahead of them. It is fair because it is in order.

Computers queue things the same way: print jobs wait for the printer, messages wait to be sent, customers wait for a support agent.

The idea in one sentence: a queue adds items at the back and removes them from the front: the first item in is the first item out (FIFO, first in, first out).

Its words:

  • enqueue: join at the back
  • dequeue: leave from the front, and give back who left
  • front and back: the two ends
  • deque (say "deck"): a double-ended queue, Python's tool for both ends

How it works in Python, step by step:

  1. from collections import deque, then line = deque()
  2. join: line.append(x)
  3. serve: line.popleft()
  4. who is next?: line[0]; how many?: len(line)

Watch the line at the counter. The panel counts what a plain list would have had to move:

Why it is correct. People only join at the back and only leave from the front, so the line keeps the order they arrived in: whoever is at the front has waited longest.

Why not a list? A list keeps its items in a row of boxes (Chapter 34). pop(0) empties box 0, so every other item moves one box to the left: n − 1 moves for a line of n. A deque is built differently: its items sit in small linked blocks with free room at both ends, so append and popleft are each O(1), with nothing to move.

What it costs, worked out. Serving everyone in a line of n, one at a time:

  • with list.pop(0): (n − 1) + (n − 2) + … + 1 = n(n − 1)/2 moves; for 100,000 people, about 5 billion
  • with deque.popleft(): 100,000 steps

Memory is O(n) either way.

from collections import deque

class Queue:
    def __init__(self):
        self.items = deque()

    def enqueue(self, x):
        self.items.append(x)          # join at the back

    def dequeue(self):
        if not self.items:
            raise IndexError("dequeue from an empty queue")
        return self.items.popleft()   # leave from the front

    def peek(self):
        return self.items[0]

    def __len__(self):
        return len(self.items)

counter = Queue()
for name in ["Rina", "Ali", "Mitu"]:
    counter.enqueue(name)
print(counter.dequeue(), "is served;", counter.peek(), "is next;", len(counter), "waiting")
from collections import deque

d = deque([2, 3])
d.append(4)          # back
d.appendleft(1)      # front
print(list(d))
print(d.popleft(), d.pop(), list(d))
A deque works at both ends: append and pop at the back, appendleft and popleft at the front, all O(1). Used as a queue you only need append and popleft.

Mistakes and edge cases.

  • line.pop() takes from the back: the newest person, which makes it a stack
  • popleft() on an empty deque raises IndexError: pop from an empty deque: check if line: first
  • list.pop(0) and list.insert(0, x) give the right answers but cost O(n) each
  • reaching into the middle of a deque (line[i] far from the ends) is O(n): a queue only needs its ends

Quiz

  1. What does this print?

    from collections import deque
    
    line = deque(["Rina", "Ali"])
    line.append("Mitu")
    first = line.popleft()
    line.append(first)
    print(list(line))
  2. Serving a whole line of n people with list.pop(0), one at a time, costs about:

    • n(n − 1)/2 moves: O(n²)
    • n moves: O(n)
    • 1 move: O(1)
  3. Which deque method serves the person at the front?

    • popleft()
    • pop()
    • appendleft()
  4. This queue serves the newest person instead of the one who waited longest. Which line is wrong?

    from collections import deque
    
    class Queue:
        def __init__(self):
            self.items = deque()
        def enqueue(self, x):
            self.items.append(x)
        def dequeue(self):
            return self.items.pop()
  5. What does this print?

    from collections import deque
    
    d = deque([1, 2, 3])
    d.appendleft(0)
    d.pop()
    print(list(d))

Coding tasks

  1. Fix the class Queue so it is first in, first out: enqueue(x) joins at the back, dequeue() gives back the one who waited longest, peek() shows who is next, plus is_empty() and len(). dequeue() and peek() on an empty queue must raise IndexError.

  2. Pass the pillow: children sit in a circle in the order of names, and the pillow starts with the first child. Each round it is passed on k times, then whoever holds it leaves the circle and the pillow goes to the next child. Write pillow_game(names, k) with a deque: the names in the order they leave (the last one is the winner).