Published on

FIFO Queue in Python

Authors

Python has built-in support for First-in-first-out (FIFO) queues:

import queueimport queue

# A FIFO queue means entries will be received in the order they were enqueued

q = queue.Queue()

for i in range(5):
    q.put(i)

while not q.empty():
    print(q.get())

The following shows the execution of this code in the python REPL:

% python
Python 3.10.6 (main, Sep  3 2022, 11:53:02) [Clang 13.0.0 (clang-1300.0.29.30)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import queue
>>> q = queue.Queue()
>>> for i in range(5):
...     q.put(i)
...
>>> while not q.empty():
...     print(q.get())
...
0
1
2
3
4

Notice how the first element put to the queue will be the first element returned on a call to get.

Once again python lives up to having "batteries included"!

If you're interested, here's an article on how to implement a FIFO queue in python with constant time put and get methods:

Python Algorithms - Implementing a FIFO Queue Using a Linked List