Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

How to implement a queue with maximum length in Python

📅 2013-Mar-23 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ deque, python, queue ⬩ 📚 Archive

In some applications, you might need to implement a queue that starts off empty, but you want it to grow and be limited to a certain length. Such a queue with a maximum length can be implemented easily using deque:

# Queue with max length of 3

from collections import deque

q = deque( maxlen=3 )
# deque([])

q.append( 10 )
q.append( 20 )
q.append( 30 )
# deque([ 10, 20, 30 ])

q.append( 40 )
# deque([ 20, 30, 40 ])

Tried with: Python 2.7.3