Open In App

Enqueue in Queues in Python

A queue is a basic data structure that follows the First-In-First-Out (FIFO) principle. At the back of the queue, elements are added (enqueued), and at the front, they are removed (dequeued). In this article, we will see the methods of Enqueuing (adding elements) in Python.

  • Enqueue: The act of adding an element to the rear (back) of the queue.
  • Dequeue: The act of removing an element from the front of the queue.
  • FIFO (First-In-First-Out): Elements are processed in the order they are added. The first element added will be the first element removed.

Know More about Queues in Python Click Here

Enqueue in Queues in Python

Below, are the methods of Enqueue in Queues in Python.

Enqueue in Queues Using collections.deque

In this example, below Python code uses the deque module to create a queue. Elements like "apple", "banana", and "cherry" are enqueued into the queue using the append() method. Finally, the content of the queue is printed, showing the order of elements added to it.

from collections import deque

# Create a queue
queue = deque()

# Enqueue elements
queue.append("apple")
queue.append("banana")
queue.append("cherry")

print(queue)  

Output
deque(['apple', 'banana', 'cherry'])

Enqueue in Queues Using Custom Queue Class

In this example, below code defines a Queue class with methods for enqueueing items. Instances maintain a list of items internally. Items are enqueued using the enqueue() method, but directly accessing the list for queue functionality isn't recommended.

class Queue:
  def __init__(self):
    self.items = []

  def enqueue(self, item):
    self.items.append(item)

# Create a queue
queue = Queue()

# Enqueue elements
queue.enqueue("orange")
queue.enqueue("mango")
queue.enqueue("grapefruit")

# Accessing elements directly from the list is not recommended
# for queue functionality (use dequeue method instead)
print(queue.items)  

Output
['orange', 'mango', 'grapefruit']
Article Tags :