0
0
PythonHow-ToBeginner · 3 min read

How to Implement Queue in Python: Simple Guide and Examples

You can implement a queue in Python using the collections.deque class for fast appends and pops or the queue.Queue class for thread-safe operations. Both allow adding items at the end and removing from the front, following the FIFO (First In, First Out) principle.
📐

Syntax

The most common way to implement a queue in Python is using collections.deque. You create a queue by initializing a deque object. Use append() to add items to the end and popleft() to remove items from the front.

Alternatively, queue.Queue provides a thread-safe queue with put() to add and get() to remove items.

python
from collections import deque

queue = deque()
queue.append(item)      # Add item to the queue
queue.popleft()         # Remove item from the queue

# Using queue.Queue
import queue
q = queue.Queue()
q.put(item)             # Add item
q.get()                 # Remove item
💻

Example

This example shows how to create a queue using collections.deque, add three items, and remove them in FIFO order.

python
from collections import deque

queue = deque()

# Add items
queue.append('apple')
queue.append('banana')
queue.append('cherry')

# Remove items
while queue:
    item = queue.popleft()
    print(item)
Output
apple banana cherry
⚠️

Common Pitfalls

One common mistake is using a Python list as a queue by appending and popping from the front with pop(0). This is inefficient because removing the first element shifts all others, causing slow performance.

Instead, use collections.deque which is optimized for fast appends and pops from both ends.

python
queue = []

# Inefficient way
queue.append('apple')
queue.append('banana')
queue.append('cherry')

print(queue.pop(0))  # Removes 'apple' but slow for large lists

# Efficient way
from collections import deque
queue = deque()
queue.append('apple')
queue.append('banana')
queue.append('cherry')
print(queue.popleft())  # Fast removal
Output
apple apple
📊

Quick Reference

Operationcollections.dequequeue.Queue
Create queuequeue = deque()q = queue.Queue()
Add itemqueue.append(item)q.put(item)
Remove itemqueue.popleft()q.get()
Check emptylen(queue) == 0q.empty()

Key Takeaways

Use collections.deque for an efficient, simple queue implementation.
Avoid using list.pop(0) for queues due to slow performance.
queue.Queue is useful for thread-safe queue operations.
Add items with append()/put() and remove with popleft()/get().
Check if queue is empty with len() for deque or empty() for queue.Queue.