How to implement a queue with maximum length in Python

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 ])

view raw
queueMaxLen.py
hosted with ❤ by GitHub

Tried with: Python 2.7.3

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.