Searching for Queue in Python programming? In this tutorial, we will discuss how to create and use queue in Python.
Customers waiting in line in a bank and jobs waiting to be printed by a printer have something in common. Each one is an example of a Queue, a sequence of objects waiting in line. The first object leaves the queue first, and the last object in the queue is the last one to leave.
What is a Python Queue Data Structure?
A python Queue is a linear data structure with which we carry out insertions at one end (called the Rear, Back, or Tail), and deletions at the other end (called the Front, or Head). Since items in a queue are processed on a First come, First Served basis, queues are referred to as FIFO data structures (FIFO: First In, First Out).
We can carry out the following operations on a Queue
- Add an item to the Rear of a Queue, or Enqueue an item.
- Remove an item from the Front of a Queue, or Dequeue an item
- Check for empty Queue
- Check for full Queue, if the Queue has a fixed capacity
- Check the Front item of a Queue
- Check the Rear item of a Queue
- Get the queue’s capacity
- Get the number of items in a queue
- Print out the whole Queue
There are several implementations of queues in python, namely, the deque in the collections module, and the Queue and PriorityQueue classes in the queue module. In this tutorial, we will be creating our very own Queue class using a list to store the queue items.
How to make a Queue of fixed capacity?
We will use a list to implement a fixed capacity queue in python. Since we are making use of a list, we will use list index 0 as the front item, and list index -1 as the back, or rear, item of the queue. The following code listing contains the class definition
class Queue:
def __init__(self, capacity=0):
super().__init__()
self.__items = list()
self.__capacity = 0 if capacity < 0 else capacity
def is_empty(self):
return (len(self.__items) == 0)
def is_full(self):
if (self.__capacity <= 0):
# this is an infinite capacity queue
# can never be filled
return False
else:
# this is a fixed capacity queue
return (len(self.__items) == self.__capacity)
def head(self):
if not(self.is_empty()):
return self.__items[0]
else:
# return None since queue is empty
return None
def tail(self):
if not(self.is_empty()):
return self.__items[-1]
else:
# return None since queue is empty
return None
def get_capacity(self):
# return the capacity of the queue
return self.__capacity
def __len__(self):
return len(self.__items)
def __str__(self):
return f"queue({str(self.__items)})"
def enqueue(self, item):
if not(self.is_full()):
self.__items.append(item)
# enqueue succeeded
return True
else:
# enqueue failed since queue is full
return False
def dequeue(self):
if not(self.is_empty()):
return self.__items.pop(0)
else:
# return None since queue is empty
return None
The attribute self.__items
stores the items in the queue, while self.__capacity
holds the capacity of the queue, or the maximum number of items that can be held by the queue. When we create a queue object, the initializer, __init()__
, initializes self.__items
to an empty list.
__init()__
accepts a parameter, capacity
, which tells the queue class the maximum number of items that should be stored by this new instance. If the value of capacity
is equal to zero, the queue becomes an infinite length queue.
Method definition of Queue in Python
The Queue class has the following method definitions:
- is_empty(): Returns a boolean value denoting if the queue is empty or not. Since it uses a list to implement the queue, it checks if the length of the list equals to zero. Then it returns a boolean based on that comparison.
- is_full(): Returns a boolean value denoting if the queue is filled up.
is_full()
returnsFalse
if the queue is not a fixed capacity queue. However, if it is a fixed capacity queue, it checks if the length of the list equals to the capacity of the queue. Then, it returns a boolean based on that comparison. - head(): Returns the front element of the queue. It returns the first element of the internal list if the list is not empty. Otherwise, it returns
None
. - tail(): Returns the back element of the queue. It returns the last element of the internal list if the list is not empty. Otherwise, it returns
None
. - get_capacity(): Returns an int representing the capacity of the Queue object.
- __len__(): Returns the number of items in the queue. Queue class overloads the base dunder method
__len()__
to allow users also have a length function work on queue objects. - __str__(): Returns a string representation of the current Queue object. When print() takes a Queue object as one of its arguments, it implicitly calls
__str()__
to get the string representation of the Queue object. - enqueue(): Returns a boolean denoting success in adding an item to the rear end of the queue.
- dequeue(): Removes and returns the front item of the Queue, or returns
None
if the Queue Object is empty.
Using the Python Queue Class
The following code makes use of the Queue class to manage a queue of customers in a Bank
def display_status(q: Queue):
print(q)
print(f"Front: {q.head()}, Rear: {q.tail()}")
print(f"Length: {len(q)}, Capacity: {q.get_capacity()}")
print(f"Is Empty: {q.is_empty()}")
print(f"Is Full: {q.is_full()}")
print("\n")
def add_status(val: bool):
if val == True:
return "Success"
else:
return "Failure"
# create the queue
customer_queue = Queue(capacity=5)
# display status
display_status(customer_queue)
# add 3 customers to the queue
print(f"Adding customer ... {add_status(customer_queue.enqueue('Gary'))}")
print(f"Adding customer ... {add_status(customer_queue.enqueue('Priyanka'))}")
print(f"Adding customer ... {add_status(customer_queue.enqueue('Chang'))}")
print("\n")
# display status
display_status(customer_queue)
# remove a customer from the queue
print(f"Serving customer {customer_queue.head()} ...")
print(f"Removing customer {customer_queue.dequeue()}")
print("\n")
# display status
display_status(customer_queue)
# add 4 customers to the queue
print(f"Adding customer ... {add_status(customer_queue.enqueue('Faulkner'))}")
print(f"Adding customer ... {add_status(customer_queue.enqueue('Ahmad'))}")
print(f"Adding customer ... {add_status(customer_queue.enqueue('Ming'))}")
print(f"Adding customer ... {add_status(customer_queue.enqueue('Carlos'))}")
print("\n")
# display status
display_status(customer_queue)
# remove all 4 customer from the queue
for count in range(0, len(customer_queue)):
print(f"Serving customer {customer_queue.head()} ...")
print(f"Removing customer {customer_queue.dequeue()}", "\n")
# display status
display_status(customer_queue)
The program creates a queue with a capacity of 5 items. The program then adds three customers to the queue, and succeeds in doing so because the queue still has space for two more customers.
The program then removes a customer, allowing space for only 3 more customers to join the queue. Then, it tries to add 4 customers and fails when trying to add the fourth customer because, by then, the queue is filled up.
Finally, the program uses a for loop to remove all the customers from the queue.
When we run the example, we get the following output
Output:
queue([])
Front: None, Rear: None
Length: 0, Capacity: 5
Is Empty: True
Is Full: False
Adding customer ... Success
Adding customer ... Success
Adding customer ... Success
queue(['Gary', 'Priyanka', 'Chang'])
Front: Gary, Rear: Chang
Length: 3, Capacity: 5
Is Empty: False
Is Full: False
Serving customer Gary ...
Removing customer Gary
queue(['Priyanka', 'Chang'])
Front: Priyanka, Rear: Chang
Length: 2, Capacity: 5
Is Empty: False
Is Full: False
Adding customer ... Success
Adding customer ... Success
Adding customer ... Success
Adding customer ... Failure
queue(['Priyanka', 'Chang', 'Faulkner', 'Ahmad', 'Ming'])
Front: Priyanka, Rear: Ming
Length: 5, Capacity: 5
Is Empty: False
Is Full: True
Serving customer Priyanka ...
Removing customer Priyanka
Serving customer Chang ...
Removing customer Chang
Serving customer Faulkner ...
Removing customer Faulkner
Serving customer Ahmad ...
Removing customer Ahmad
Serving customer Ming ...
Removing customer Ming
queue([])
Front: None, Rear: None
Length: 0, Capacity: 5
Is Empty: True
Is Full: False
The function display_status()
displays the status of the queue. The function add_status()
converts a boolean value into a string message saying “Success” or “Failure”. add_status()
provides a more descriptive message concerning whether enqueueing an item succeeded than just saying True
or False
.
Conclusion
This ends our tutorial on queues in python. We discussed how to implement our own queue class using a list as the underlying structure. Thanks for reading!
If you need homework help python or looking for someone who can python help then feel free to drop us a message.