Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

How to use queue in Python

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

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

Tried with: Python 2.7.3


© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘 @codeyarns@hachyderm.io📧