Skip to main content
Practice

Queue: First In, First Out Data Structure

A Queue is a data structure where the first data entered is the first one to be removed, following the First In, First Out (FIFO) principle.

It functions like a queue in daily life, where data is processed sequentially.

Queues are used in scenarios such as job scheduling, where tasks are processed in the order they were requested, or in printer task queues.


Key Operations of Queue

Based on the FIFO principle, a queue offers the following key operations:

  1. Enqueue: Add an element to the back (tail) of the queue. The newly added element will occupy the last position in the queue.

  2. Dequeue: Remove and return an element from the front (head) of the queue. Once removed, the next element occupies the new front.

  3. Peek or Front: Check the element at the front of the queue. The checked element remains in place.

  4. IsEmpty: Check if the queue is empty. Returns True if there are no elements in the queue, otherwise False.


How is a Queue Implemented?

In Python, a queue can be implemented using a list, but for better efficiency, the deque class from the collections module is preferred.

deque is a data structure that allows appending or popping elements from both ends efficiently.

Queue Implementation Example
# Importing the deque class from collections module
from collections import deque

# Create a queue
queue = deque()

# Enqueue operations
queue.append('A') # Add A
queue.append('B') # Add B

# Dequeue operations
print(queue.popleft()) # Output and remove 'A'
print(queue.popleft()) # Output and remove 'B'

You can explore a more detailed example of implementing a queue using a Class in the code editor located on the right.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.