Back to Data Structures & Algorithms
2026-03-306 min read

Basic Operations of Queue (Data Structures & Algorithms)

Learn Basic Operations of Queue (Data Structures & Algorithms) step by step with clear examples and exercises.

Why This Matters

Understanding the basic operations of a queue is crucial for solving real-world problems such as managing tasks in an operating system, simulating network traffic, or optimizing web server requests. Being proficient with queues can help you excel in coding interviews and exams that test your data structures and algorithms knowledge.

Importance of Queues

Queues are essential for maintaining the order of processing in various scenarios, ensuring that tasks are completed efficiently and effectively. They play a significant role in managing resources, scheduling events, and handling requests in real-world applications.

Prerequisites

Before diving into the core concept of queues, it's essential to have a good understanding of the following:

  1. Python programming basics, including variables, functions, loops, conditional statements, exceptions, and list comprehensions.
  2. Data structures like lists and tuples.
  3. Basic concepts of algorithms and their complexity analysis.
  4. Understanding of objects and classes in Python.
  5. Familiarity with exception handling in Python.
  6. Knowledge of list slicing and the modulo operator (%).

Core Concept

A queue is a linear data structure that follows a First-In-First-Out (FIFO) principle. This means that the first element added to the queue is the first one to be removed. Queues are useful for scenarios where you need to maintain the order of processing, such as printing documents or managing tasks in an operating system.

Implementing a Queue in Python (Expanded)

Python provides a built-in module called collections that includes a queue data structure. To use it, import the Queue class and create an instance:

from collections import deque
my_queue = deque()

You can add elements to the queue using the append method or by simply assigning values to the queue object:

my_queue.append(1)
my_queue.append(2)
my_queue.append(3)
my_queue = [4, 5, 6] + my_queue

To remove elements from the queue, use the popleft method:

print(my_queue.popleft()) # Output: 1
print(my_queue) # Output: deque([2, 3, 4, 5, 6])

You can also check the current size of the queue using the len function:

print(len(my_queue)) # Output: 5

Customizing a Queue in Python (Expanded)

To create a custom queue with specific elements, you can define your own class and use it in place of built-in types like integers or strings. Here's an example using a custom Person class:

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def __repr__(self):
return f"Person({self.name}, {self.age})"

my_queue = deque([Person("Alice", 25), Person("Bob", 30)])
print(my_queue[0]) # Output: Person(Alice, 25)

Common Mistakes (Expanded)

  1. Forgetting to import the deque module: Make sure you have from collections import deque at the beginning of your script.
  2. Using appendleft instead of append: Remember that append adds elements to the end of the queue, while appendleft adds them to the front.
  3. Not checking if the queue is empty before removing elements: Always use a conditional statement to check if the queue is empty before trying to remove elements to avoid errors.
  4. Misunderstanding the FIFO principle: Remember that the first element added to the queue is the first one to be removed.
  5. Not handling exceptions when using sleep() function: Ensure you handle potential KeyboardInterrupt or RuntimeError exceptions when using the time.sleep() function.
  6. Ignoring the worst-case time complexity of append and popleft operations: Both append and popleft have an average time complexity of O(1), but their worst-case time complexity is O(n) when resizing the underlying list.
  7. Creating an infinite loop when iterating through a queue: Make sure to check if the queue is empty before starting or continuing the loop to avoid an infinite loop.
  8. Not considering the size of the queue when implementing custom operations: When working with custom classes, ensure that your operations handle the specific size and structure of the elements in the queue.

Worked Example

Let's create a simple example where we use a queue to manage tasks in an operating system. We will simulate multiple tasks arriving at different times and process them based on their arrival order:

from collections import deque
import time

class Task:
def __init__(self, name, arrival_time):
self.name = name
self.arrival_time = arrival_time

def __repr__(self):
return f"Task({self.name}, {self.arrival_time})"

def main():
tasks = deque()
task_queue = [Task("Print document 1", 0), Task("Compile code 2", 1),
Task("Render video 3", 2), Task("Backup data 4", 3)]

print("Arrival times of tasks:")
for task in task_queue:
print(task)

while task_queue:
current_time = len(tasks)
if not tasks or current_time > task_queue[0].arrival_time:
tasks.append(task_queue.popleft())
if tasks:
print(f"Processing {tasks[0]} at time: {current_time}")
tasks.popleft()
time.sleep(1) # Simulate processing time

print("All tasks have been processed.")

if __name__ == "__main__":
main()

Practice Questions

  1. Write a Python program that implements a priority queue using a list of tuples, where each tuple contains an element and its priority. The dequeue should follow the principle of highest-priority-first (HPF).
  2. Implement a function dequeue_n(my_queue, n) in Python that removes n elements from the queue my_queue.
  3. Write a Python program that simulates a bank teller serving customers based on their arrival order using a queue data structure. Customers should be represented as objects with attributes like name and time of arrival.
  4. Implement a function find_closest_pair(my_queue) in Python that finds the two closest elements (in terms of index positions) in a given queue my_queue.
  5. Write a Python program that implements a custom queue using a linked list data structure instead of an array. The queue should support append, popleft, and checking if the queue is empty operations.

Common Mistakes

  1. Forgetting to import the deque module: Make sure you have from collections import deque at the beginning of your script.
  2. Using appendleft instead of append: Remember that append adds elements to the end of the queue, while appendleft adds them to the front.
  3. Not checking if the queue is empty before removing elements: Always use a conditional statement to check if the queue is empty before trying to remove elements to avoid errors.
  4. Misunderstanding the FIFO principle: Remember that the first element added to the queue is the first one to be removed.
  5. Not handling exceptions when using sleep() function: Ensure you handle potential KeyboardInterrupt or RuntimeError exceptions when using the time.sleep() function.
  6. Ignoring the worst-case time complexity of append and popleft operations: Both append and popleft have an average time complexity of O(1), but their worst-case time complexity is O(n) when resizing the underlying list.
  7. Creating an infinite loop when iterating through a queue: Make sure to check if the queue is empty before starting or continuing the loop to avoid an infinite loop.
  8. Not considering the size of the queue when implementing custom operations: When working with custom classes, ensure that your operations handle the specific size and structure of the elements in the queue.

FAQ

What is a queue in Python?

A queue is a linear data structure that follows a First-In-First-Out (FIFO) principle. It maintains the order of elements, with the first element added being the first one to be removed.

How do I create a custom queue in Python using a linked list?

To create a custom queue using a linked list, you can define your own Node class and implement the necessary methods for append, popleft, and checking if the queue is empty operations.

What is the time complexity of append and popleft operations in a Python queue?

Both append and popleft have an average time complexity of O(1), but their worst-case time complexity is O(n) when resizing the underlying list.

How can I find the two closest elements in a given queue?

To find the two closest elements (in terms of index positions) in a given queue, you can iterate through the queue and keep track of the indices of the first and second closest elements.

What are some common mistakes when working with queues in Python?

Common mistakes include forgetting to import the deque module, using appendleft instead of append, not checking if the queue is empty before removing elements, misunderstanding the FIFO principle, ignoring exceptions when using sleep(), and creating an infinite loop when iterating through a queue.

Basic Operations of Queue (Data Structures & Algorithms) | Data Structures & Algorithms | XQA Learn