How to use queue in Python

The ubiquitous list can be used as a queue in Python. But, that is not efficient because of the way lists are implemented.

Using deque from the collections module is a straightforward way to use queues:

# remove <– [….] <– insert
# Queue with insertion from right and removal from left
from collections import deque
q = deque()
# deque([])
q.append( 10 )
# deque([ 10 ])
q.append( 50 )
# deque([ 10, 50 ])
q.append( 30 )
# deque([ 10, 50, 30])
q.popleft()
# 10

view raw
queue.py
hosted with ❤ by GitHub

Tried with: Python 2.7.3

2 thoughts on “How to use queue in Python

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.