Skip to content
Concept ยท Data Structures and Algorithms

Queue data structure: types and Python implementation

Younus FardeenBy Younus FardeenUpdated 1 Dec 20268 min read
Short answer

A queue is a linear data structure that follows first in, first out (FIFO): items are added at the rear and removed from the front. The main types are the simple queue, circular queue, double-ended queue (deque) and priority queue. In Python, use collections.deque, because list.pop(0) takes O(n) time.

On this pageWhat is a queue and what are its operations?Types of queueWhy collections.deque beats list.pop(0)Queue in action: breadth-first searchInterview traps and practiceFrequently asked questions

This page covers the four queue types students are asked about, one working Python implementation of each, and a measurement of the mistake that slows most beginner queues. Code was run on Python 3.9.6 on 1 December 2026.

For real-world uses (printers, ticket booking, message brokers) read applications of queue in data structure. The mirror structure is the stack.

What is a queue and what are its operations?

A queue is a line. New items join at the rear, and the item that has waited longest leaves from the front. The two main operations are enqueue (add at the rear) and dequeue (remove from the front). Most implementations also offer peek or front, is_empty and size.

OperationMeaningTime (good implementation)
enqueue(x)Add x at the rearO(1)
dequeue()Remove and return the front itemO(1)
front() / peek()Read the front itemO(1)
is_empty(), size()State checksO(1)

Put the words in the right order: queue is FIFO, stack is LIFO. In Python the simplest correct queue is collections.deque.

from collections import deque

q = deque()
q.append("A"); q.append("B"); q.append("C")   # enqueue at the rear
print(q.popleft(), q[0], len(q))              # dequeue from the front, peek
print(q)
A B 2
deque(['B', 'C'])

Types of queue

TypeRuleTypical usePython tool
Simple (linear) queueFIFO, insert at rear, remove at frontPrint jobs, request linescollections.deque
Circular queueFixed buffer; the end wraps to the startStreaming buffers, keyboard buffersList with modulo indexes
Deque (double-ended)Insert and remove at both endsSliding window, undo with limitcollections.deque
Priority queueItem with the highest priority leaves firstTask schedulers, Dijkstraheapq or queue.PriorityQueue

Circular queue

A simple array queue wastes space: after dequeues, the front slots are empty but the rear may be at the end. A circular queue fixes this by wrapping the index back to 0 with a modulo. It needs a fixed capacity and a way to tell full from empty; here a size counter does that.

class CircularQueue:
    def __init__(self, capacity):
        self.buf = [None] * capacity
        self.cap = capacity
        self.head = 0        # index of the front item
        self.size = 0
    def enqueue(self, x):
        if self.size == self.cap:
            raise OverflowError("queue is full")
        self.buf[(self.head + self.size) % self.cap] = x
        self.size += 1
    def dequeue(self):
        if self.size == 0:
            raise IndexError("queue is empty")
        x = self.buf[self.head]
        self.buf[self.head] = None
        self.head = (self.head + 1) % self.cap
        self.size -= 1
        return x

q = CircularQueue(3)
for x in [1, 2, 3]:
    q.enqueue(x)
print(q.dequeue(), q.dequeue())
q.enqueue(4); q.enqueue(5)          # these wrap around to index 0 and 1
print(q.buf, "head =", q.head)
try:
    q.enqueue(6)
except OverflowError as e:
    print("error:", e)
1 2
[4, 5, 3] head = 2
error: queue is full

After removing 1 and 2, adding 4 and 5 reuses slots 0 and 1, so buf is [4, 5, 3] and the front (head) is index 2. Adding a sixth item fails because the queue holds 3 already.

Deque (double-ended queue)

A deque allows push and pop at both ends in O(1). Python's deque documentation describes thread-safe, memory efficient appends and pops from either side, and a maxlen option that keeps only the newest items.

from collections import deque

d = deque([2, 3])
d.appendleft(1)
d.append(4)
print(d)
print(d.popleft(), d.pop(), d)

# bounded deque: keeps only the last 3 items
last3 = deque(maxlen=3)
for x in range(6):
    last3.append(x)
print(last3)
deque([1, 2, 3, 4])
1 4 deque([2, 3])
deque([3, 4, 5], maxlen=3)

Priority queue

Here order depends on priority, not arrival. The usual implementation is a binary heap, which gives O(log n) insert and O(log n) removal of the smallest item. Python's heapq is a min-heap, so a smaller number means higher priority. Tuples compare left to right, so the task name breaks ties.

import heapq

pq = []
for priority, task in [(3, "email"), (1, "fix prod bug"), (2, "review PR"), (1, "page on-call")]:
    heapq.heappush(pq, (priority, task))

while pq:
    print(heapq.heappop(pq))
(1, 'fix prod bug')
(1, 'page on-call')
(2, 'review PR')
(3, 'email')

Note that a priority queue is not strictly FIFO: email arrived first but left last. Equal priorities come out in alphabetical order here because the tuple compares the second item, not because of arrival time. If you need arrival order on ties, add a counter as the second tuple element.

Why collections.deque beats list.pop(0)

A Python list is an array. Removing from the front means every remaining item shifts one place left, so pop(0) is O(n). The Python docs say the same: lists incur O(n) memory movement costs for pop(0) and insert(0, v). A deque has O(1) at both ends. This script measures it.

import timeit
from collections import deque

for n in (10_000, 100_000):
    def with_list():
        a = list(range(n))
        while a:
            a.pop(0)
    def with_deque():
        d = deque(range(n))
        while d:
            d.popleft()
    t_list = timeit.timeit(with_list, number=1)
    t_deque = timeit.timeit(with_deque, number=1)
    print(f"n={n:>7}: list.pop(0) {t_list*1000:8.1f} ms | deque.popleft {t_deque*1000:6.1f} ms | ratio {t_list/t_deque:5.0f}x")
n=  10000: list.pop(0)      6.2 ms | deque.popleft    0.4 ms | ratio    16x
n= 100000: list.pop(0)    794.6 ms | deque.popleft    4.3 ms | ratio   185x

That output is from one run on a laptop; your numbers will differ, but the shape will not. Going from 10,000 to 100,000 items made the list version far slower than 10 times, because its total cost grows with the square of the size, while the deque grew roughly linearly. At a few hundred items you will not notice. At a hundred thousand you will. For the full cost model see time complexity and Big O.

Also note what a deque gives up: indexing in the middle is O(n), unlike a list. If you need both fast front removal and random access, rethink the design.

Breadth-first search (BFS) explores a graph level by level, and a queue supplies that order: visit the oldest discovered node first. Because every edge has the same cost, the first time BFS reaches a node is by a shortest path in number of edges. This works on the graph in the code below, stored as an adjacency list; see graph data structure explained.

from collections import deque

graph = {"A": ["B", "C"], "B": ["D"], "C": ["D", "E"], "D": ["F"], "E": ["F"], "F": []}

def bfs_shortest(graph, start, goal):
    queue = deque([[start]])
    seen = {start}
    while queue:
        path = queue.popleft()
        node = path[-1]
        if node == goal:
            return path
        for nxt in graph[node]:
            if nxt not in seen:
                seen.add(nxt)
                queue.append(path + [nxt])
    return None

print(bfs_shortest(graph, "A", "F"))
['A', 'B', 'D', 'F']

Both A to B to D to F and A to C to E to F have three edges; BFS returns the first one it finds. Mark nodes as seen when you enqueue them, not when you dequeue them, or the same node can enter the queue many times.

Interview traps and practice

The classic question is a queue built from two stacks. Elements move from the inbox stack to the outbox stack only when the outbox is empty, which makes dequeue O(1) amortised.

from collections import deque

class TwoStackQueue:
    """Queue built from two stacks (a classic interview question)."""
    def __init__(self):
        self.inbox, self.outbox = [], []
    def enqueue(self, x):
        self.inbox.append(x)
    def dequeue(self):
        if not self.outbox:
            while self.inbox:
                self.outbox.append(self.inbox.pop())
        return self.outbox.pop()

q = TwoStackQueue()
for x in [1, 2, 3]:
    q.enqueue(x)
print(q.dequeue(), q.dequeue())
q.enqueue(4)
print(q.dequeue(), q.dequeue())
1 2
3 4
  • Using list.pop(0) in a BFS and getting a timeout on large inputs.
  • Forgetting the full-versus-empty ambiguity in a circular queue (use a size counter or leave one slot free).
  • Treating a priority queue as FIFO.
  • Returning from dequeue on an empty queue without raising or signalling an error.
  • Implementing a queue with two stacks but moving items on every dequeue instead of only when the outbox is empty.

Next: practise sliding window maximum with a deque, rotting oranges and word ladder with BFS, and top-k elements with a heap. The wider order of topics is on the data structures and algorithms learning path, with more questions in DSA interview questions.

Frequently asked questions

What is a queue in a data structure?

A queue is a linear collection that follows first in, first out (FIFO). You add items at the rear (enqueue) and remove them from the front (dequeue). The item that has waited longest is served first, like people in a ticket line.

What are the types of queue?

Four are standard: the simple or linear queue, the circular queue, the double-ended queue (deque) and the priority queue. Some textbooks also list input-restricted and output-restricted deques, which are deques that only allow insertion or removal at one end.

What is a circular queue and why use it?

A circular queue treats a fixed-size array as a ring, so the rear index wraps to the start using modulo. It reuses slots freed by dequeues, which a plain array queue wastes. It is common for fixed buffers such as keyboard or streaming input.

How is a priority queue different from a normal queue?

A normal queue removes the oldest item. A priority queue removes the item with the highest priority, whatever its arrival time. It is usually built on a binary heap, giving O(log n) insert and removal.

How do you implement a queue in Python?

Use collections.deque with append to enqueue and popleft to dequeue, both O(1). Avoid list.pop(0), which is O(n) because it shifts every item. For thread-safe producer and consumer code, queue.Queue is the standard choice.

What is the time complexity of queue operations?

Enqueue, dequeue, front and is_empty are all O(1) in a linked list, circular array or deque. A list used as a queue makes dequeue O(n). A heap-based priority queue is O(log n) for insert and remove.

Learn this with mentors

Programmes for builders and engineers with admissions open: live classes, mentors and project work.

Continue learning

Explainer

Applications of queue

Where queues are used: scheduling, BFS, buffers, with code.

3 min read
Concept

Stack data structure

Push, pop, peek, the call stack and two worked interview problems in Python

6 min read
Concept

Graph data structure

Vertices, edges, BFS, DFS and cycle checks with tested code

8 min read