Skip to main content

What is a Queue?

A Queue is a linear data structure that follows the FIFO (First-In, First-Out) principle. The element that enters first is the one that gets removed first. Think of it like a line of people waiting to buy tickets: the person at the front of the line is served first, and new people join the line at the back.
  • Enqueue: Adding an element to the back of the queue.
  • Dequeue: Removing an element from the front of the queue.

Why NOT to use standard Lists for Queues

In Python, you can use a list as a queue by appending to the end and popping from the front (list.pop(0)). However, this is very inefficient:

The Performance Problem:

When you pop the first item from a standard Python list, Python must shift all subsequent items one position to the left in memory. For a list with thousands of items, this operation becomes slow and degrades program performance.

The Correct Way: collections.deque

To handle queues efficiently, Python provides the deque (double-ended queue) class in the built-in collections module. A deque is optimized for fast appends and pops from both ends, achieving O(1)O(1) constant time complexity for both enqueue and dequeue operations.

Common mistakes

To dequeue from a deque, you must use .popleft(). If you use .pop(0) on a deque, Python will raise a TypeError because deque objects do not support indexing in their pop operations.
Although deque shares many methods with standard lists (like .append()), it is a different object type. If your code needs extensive sorting or slicing (like queue[1:3]), convert the deque back to a list first using list(queue).

Practice & Exercises

To reinforce what you’ve learned in this section (FIFO structures and Deques), practice with these interactive notebooks:

Follow-Along Practice

Practice initializing deques, performing enqueues and dequeues, and comparing performance speeds.💻 VS Code | 🚀 Colab | 📥 Download

Practice Exercises

Test your knowledge with hands-on exercises on ticketing lines, customer support simulation, and error cases.💻 VS Code | 🚀 Colab | 📥 Download

What’s next?

Compare Arrays, Stacks, Queues, Maps, and Trees in our comprehensive Data Structures Summary.

Data Structures Summary

Compare implementations and CRUD operations