PythonMastery
Python programs · Functions · beginner

Queue in Python using deque

A queue is first in, first out. Use collections.deque with append() and popleft(), and see why list.pop(0) is the slow way to do it.

A queue is a collection where the first item you add is the first one you take out: first in, first out (FIFO), like people waiting in a line. collections.deque is the right tool for a queue in Python.

The program

python
from collections import deque

queue = deque()
queue.append("Ada")        # enqueue: join the back of the line
queue.append("Linus")
queue.append("Grace")
print(queue)

print(queue[0])            # look at the front without removing it
print(queue.popleft())     # dequeue: take from the front
print(queue)

while queue:
    print("serving", queue.popleft())
print("queue empty:", len(queue) == 0)
output
deque(['Ada', 'Linus', 'Grace'])
Ada
Ada
deque(['Linus', 'Grace'])
serving Linus
serving Grace
queue empty: True

How it works

A fixed-size queue

With maxlen, a deque keeps only the newest items. When it is full, adding to the back drops an item from the front. This is useful for "the last N" values, such as recent log lines:

python
from collections import deque

recent = deque(maxlen=3)
for page in ["home", "lessons", "errors", "notebook", "answers"]:
    recent.append(page)
    print(list(recent))
output
['home']
['home', 'lessons']
['home', 'lessons', 'errors']
['lessons', 'errors', 'notebook']
['errors', 'notebook', 'answers']

Related programs: Stack in Python using a list.

Learn the idea: collections: The Stdlib's Hidden Power, Lists & Sequences

A longer explanation: Take from the front of a deque, not a list