TL;DR – A Python queue is a linear data structure, similar to a stack.
How to use a queue in Python
To start building Python queues, you need to import the
queue Python module first:
Python 1.4 and all the newer versions have this module available for use. It allows you to implement Python multithreading queues:
- To add an element to the queue, use
put(). This is called an enqueue operation.
- To remove an element from the queue, use
get(). This is called a dequeue operation.
- The FIFO (First In, First Out) principle means the first element you insert will also be the first to be removed.
By using the
maxsize argument, you can choose to restrict the number of elements in a queue. To leave the size unlimited, define it as
0 or a negative number.
Theory is great, but we recommend digging deeper!
Python queue examples: four types
To create a basic Python queue, use
BitDegree = queue.Queue(maxsize=0) BitDegree.put("B") BitDegree.put("i") BitDegree.put("t") print (BitDegree.get())
You can also create a queue in Python that follows the LIFO principle (Last In, First Out). In such a case, the first element to remove will be the one that got added last. To do that, use
import queue BitDegree = queue.LifoQueue(maxsize=0) BitDegree.put("B") BitDegree.put("i") BitDegree.put("t") print (BitDegree.get())
If you need to sort your elements in a specific way, you can also create a priority queue. For that, you would use
queue.PriorityQueue(). In such a case, the first element to remove will be the one that has the lowest value:
BitDegree = queue.PriorityQueue(maxsize=0) BitDegree.put((3, "B")) BitDegree.put((1, "i")) BitDegree.put((2, "t")) print (BitDegree.get())
If you're using Python 3.7 or a newer version, you can also use
queue.SimpleQueue() to create simple Python queues with less functionalities – e.g, they will not allow task tracking:
BitDegree = queue.SimpleQueue(maxsize=0) BitDegree.put("B") BitDegree.put("i") BitDegree.put("t")
Python queue: useful tips
- To simplify working with priority queues, follow the
number, elementpattern and use the
numberto define priority.
- To create Python multiprocessing queues (as opposed to multithreading), use
multiprocessing.Queue()function for the