Open In App

Enqueue in Queues in Python

Last Updated : 16 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.

  • Using collections.deque()
  • Using Custom Queue Class

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.

Python3
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.

Python3
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']

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads