In computer science, a queue is a data structure that stores a collection of elements and operates on them based on the principle of first-in-first-out (FIFO). This means that the first element added to the queue is the first one to be removed. Queues are commonly used in programming languages, operating systems, and other applications.

Operations on a Queue

There are two primary operations that can be performed on a queue:

  1. Enqueue: Adds an element to the end of the queue.
  2. Dequeue: Removes the first element from the queue.

There are also a few other operations that can be performed on a queue:

  1. Peek: Returns the first element without removing it from the queue.
  2. Size: Returns the number of elements in the queue.
  3. IsEmpty: Checks if the queue is empty.

Implementing a Queue in Python

One way to implement a queue in Python is to use a list. Here’s some example code for a queue implementation using a list:

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

    def enqueue(self, item):

    def dequeue(self):
        return self.items.pop(0)

    def peek(self):
        return self.items[0]

    def size(self):
        return len(self.items)

    def is_empty(self):
        return len(self.items) == 0

This code defines a new class Queue, which has six methods:

Example Usage

Here’s an example of how you might use the Queue class:

q = Queue()
print(q.peek())  # prints 1
print(q.dequeue())   # prints 1
print(q.dequeue())   # prints 2
print(q.size())  # prints 1
print(q.is_empty())  # prints False

This code creates a new queue q and adds three items to it using the enqueue method. It then prints the first item using peek, removes two items using dequeue, and prints the size of the queue and whether it’s empty using size and is_empty.

Advantages of Using a Queue

Queues have several advantages in computer science:


Queues are a commonly used data structure in computer science. They operate on the principle of first-in-first-out (FIFO) and have several useful operations, including enqueue, dequeue, peek, size, and is_empty. Queues can be implemented using basic data structures such as arrays or linked lists and are efficient and memory-efficient.

Leave a Reply

Your email address will not be published. Required fields are marked *