Open In App

Queue in Python

Like a stack, the queue is a linear data structure that stores items in a First In First Out (FIFO) manner. With a queue, the least recently added item is removed first. A good example of a queue is any queue of consumers for a resource where the consumer that came first is served first.
 



Operations associated with queue are: 

Implement a Queue in Python

There are various ways to implement a queue in Python. This article covers the implementation of queue using data structures and modules from Python library. Python Queue can be implemented by the following ways:



Implementation using list

List is a Python’s built-in data structure that can be used as a queue. Instead of enqueue() and dequeue(), append() and pop() function is used. However, lists are quite slow for this purpose because inserting or deleting an element at the beginning requires shifting all of the other elements by one, requiring O(n) time.
The code simulates a queue using a Python list. It adds elements ‘a’, ‘b’, and ‘c’ to the queue and then dequeues them, resulting in an empty queue at the end. The output shows the initial queue, elements dequeued (‘a’, ‘b’, ‘c’), and the queue’s empty state.




queue = []
queue.append('a')
queue.append('b')
queue.append('c')
print("Initial queue")
print(queue)
print("\nElements dequeued from queue")
print(queue.pop(0))
print(queue.pop(0))
print(queue.pop(0))
print("\nQueue after removing elements")
print(queue)

Output: 

Initial queue
['a', 'b', 'c']
Elements dequeued from queue
a
b
c
Queue after removing elements
[]

Traceback (most recent call last):
File "/home/ef51acf025182ccd69d906e58f17b6de.py", line 25, in
print(queue.pop(0))
IndexError: pop from empty list

Implementation using collections.deque

Queue in Python can be implemented using deque class from the collections module. Deque is preferred over list in the cases where we need quicker append and pop operations from both the ends of container, as deque provides an O(1) time complexity for append and pop operations as compared to list which provides O(n) time complexity. Instead of enqueue and deque, append() and popleft() functions are used.
The code uses a deque from the collections module to represent a queue. It appends ‘a’, ‘b’, and ‘c’ to the queue and dequeues them with q.popleft(), resulting in an empty queue. Uncommenting q.popleft() after the queue is empty would raise an IndexError. The code demonstrates queue operations and handles an empty queue scenario.




from collections import deque
q = deque()
q.append('a')
q.append('b')
q.append('c')
print("Initial queue")
print(q)
print("\nElements dequeued from the queue")
print(q.popleft())
print(q.popleft())
print(q.popleft())
 
print("\nQueue after removing elements")
print(q)

Output: 
 

Initial queue
deque(['a', 'b', 'c'])
Elements dequeued from the queue
a
b
c
Queue after removing elements
deque([])
 

Traceback (most recent call last):
File "/home/b2fa8ce438c2a9f82d6c3e5da587490f.py", line 23, in
q.popleft()
IndexError: pop from an empty deque

Implementation using queue.Queue

Queue is built-in module of Python which is used to implement a queue. queue.Queue(maxsize) initializes a variable to a maximum size of maxsize. A maxsize of zero ‘0’ means a infinite queue. This Queue follows FIFO rule. 
There are various functions available in this module: 

Example: This code utilizes the Queue class from the queue module. It starts with an empty queue and fills it with ‘a’, ‘b’, and ‘c’. After dequeuing, the queue becomes empty, and ‘1’ is added. Despite being empty earlier, it remains full, as the maximum size is set to 3. The code demonstrates queue operations, including checking for fullness and emptiness.




from queue import Queue
q = Queue(maxsize = 3)
print(q.qsize())
q.put('a')
q.put('b')
q.put('c')
print("\nFull: ", q.full())
print("\nElements dequeued from the queue")
print(q.get())
print(q.get())
print(q.get())
print("\nEmpty: ", q.empty())
q.put(1)
print("\nEmpty: ", q.empty())
print("Full: ", q.full())

Output: 
 

0
Full: True
Elements dequeued from the queue
a
b
c
Empty: True
Empty: False
Full: False

 


Article Tags :