Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

Using list as queue in Python

📅 2012-Apr-18 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ list, python, queue ⬩ 📚 Archive

The humble list can be used as a simple queue in Python.

q = []

for i in range( 0, 5 ):
    q.append( i ) # Add to back of queue

while q: # Queue not empty
    j = q.pop( 0 ) # Get from front of queue
    print( j )

# Output: 0 1 2 3 4

Note that popping the first item of a list is not optimal due to the way it is implemented. For large queues, using deque as queue is a much better option.

Tried with: Python 3.2.2