Using list as queue in Python

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

Advertisements

2 thoughts on “Using list as 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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s