Python QUEUE
- Read
- Discuss
Introduction to Queue Data Structure
A queue is a linear data structure that follows the First In First Out (FIFO) principle. This means that the first element added to the queue will be the first one to be removed. A queue can be considered a list of elements where the first element added to the queue is always the first to be removed, similar to how a real-life queue works.
Let’s take an example of 4 persons standing in line to vote.
The first person in the line would be the one at the front of the queue, and the last person in the line would be at the end of the queue. Each person would be added to the back of the queue as they arrive to vote, and removed from the front of the queue as they are called to vote.
- The first person in line is “Alice.”
- “Bob” arrives and joins the line behind “Alice.”
- “Charlie” arrives and joins the line behind “Bob.”
- “David” arrives and joins the line behind “Charlie.”
Let’s see the working example of the above use case.
import queue
# Create an empty queue
voters_queue = queue.Queue()
# Add voters to the queue
voters_queue.put("Alice")
voters_queue.put("Bob")
voters_queue.put("Charlie")
voters_queue.put("David")print(voters_queue.qsize())
The following will be the output.
4
Now let’s remove the voters one by one and see who gets out first.
# Remove and print the next voter in line
print(voters_queue.get())
print(voters_queue.get())
print(voters_queue.get())
print(voters_queue.get())
# Print the number of voters still in the queue
print(voters_queue.qsize())
The following will be the output.
Alice
Bob
Charlie
David
0
- The voting process begins and “Alice” is called to vote. She is removed from the front of the queue.
- “Bob” is called to vote next and removed from the front of the queue.
- “Charlie” is called to vote next and is removed from the front of the queue.
- “David” is the last person in line and is called to vote next. He is removed from the front of the queue.
- The queue is now empty, as all voters have had the opportunity to vote.
A queue has two main operations:
- Enqueue: This operation adds an element to the end of the queue.
- Dequeue: This operation removes the front element from the queue.
In addition to these two basic operations, there are a few other commonly used operations:
- IsEmpty: This operation checks whether the queue is empty.
- Size: This operation returns the number of elements in the queue.
Queues are often implemented using arrays or linked lists. The choice of implementation depends on the specific requirements of the application.
Implement the queue in Python
There are several ways to implement a queue in Python, using both built-in data types and external libraries. Here is an example of a basic queue implementation using a list:
# Create an empty list to represent the queue
voters_queue = []
# Add "Alice" to the queue
voters_queue.append("Alice")
# "Bob" arrives and joins the line behind "Alice"
voters_queue.append("Bob")
# "Charlie" arrives and joins the line behind "Bob"
voters_queue.append("Charlie")
# "David" arrives and joins the line behind "Charlie"
voters_queue.append("David")
# The voting process begins and "Alice" is called to vote
print(voters_queue.pop(0))
# "Bob" is called to vote next
print(voters_queue.pop(0))
# "Charlie" is called to vote next
print(voters_queue.pop(0))
# "David" is the last person in line and is called to vote next
print(voters_queue.pop(0))
# The queue is now empty, as all voters have had the opportunity to vote
print(voters_queue)
The following will be the output of the above code
Alice
Bob
Charlie
David
[]
Above example is using the list to implement a queue, it’s straightforward but it’s not efficient for extensive data set since it needs to move all element once you dequeue one. For extensive data set collection. deque from the collections library is a better option, it gives better time complexity:
from collections import deque
q = deque()
q.append(1)
q.append(2)
q.append(3)
print(q.popleft()) # prints 1
print(q.popleft()) # prints 2
The following will be the output of the above code
1
2
Use Cases of Queue
There are many use cases for queues in computer science and software engineering, including
- Task scheduling: Queues are often used to schedule tasks to be executed in order, such as tasks in a batch processing system or print jobs in a printer spooler.
- Network communication: Queues can buffer incoming and outgoing network packets, allowing for smoother communication and preventing data loss.
- Resource allocation: Queues can be used to manage and allocate resources, such as memory or CPU time, to ensure that resources are used efficiently.
- Breadth-First search: Queue is used in the breadth-first search algorithm to keep track of the nodes to be visited next.
- Waiting queue: Queue can be used as a waiting queue in a number of applications such as hospitals, theme parks, and customer service desks.
- Buffer data: Queue can be used to buffer incoming data streams such as audio, and video to avoid data loss.
- Cache eviction: Queue can be used as an eviction queue in the cache eviction algorithm, it decides which elements need to be removed when the cache is full.
These are just a few examples, but queues can also be used in many other applications where a FIFO ordering of elements is needed.
Limitations of Queue
There are several limitations of queues as a data structure:
- Limited accessibility: Only the front element of the queue can be accessed at any given time. To access an element in the middle of the queue, all elements in front of it must first be removed.
- Fixed size: Queues are fixed and can’t be resized dynamically. This means that if a queue is full and a new element is enqueued, a queue overflow error will occur. On the other hand, if a queue is empty and an element is dequeued, a queue underflow error will occur.
- Limited functionality: Queues can only perform a limited set of operations, such as enqueue, dequeue, and peek. It cannot be used for operations that require random access to elements, such as sorting or searching.
- Not suitable for large data set: When the data set is large, the queue may quickly become filled, and this may cause the program to run out of memory or crash.
- No random access: Since the queue follows FIFO, we can not access any random element like other data structures such as Array, List, etc.
- Performance issues: if there are frequent insert and delete operations on the front, it may cause poor performance.
However, the limitations of queues can be overcome by using other data structures, such as stacks or linked lists, in conjunction with queues. Additionally, there are other advanced queue implementations like priority queues and double-ended queues which may overcome some of the limitations.
Leave a Reply
You must be logged in to post a comment.