Sobes.tech
Junior

What do you know about the data structure 'queue'?

sobes.tech AI

Answer from AI

Queue — a linear data structure that operates on the FIFO (First-In, First-Out) principle: the first element added is the first to be removed.

Main operations:

  • put/enqueue: add an element to the end of the queue.
  • get/dequeue: remove and return the element from the beginning of the queue.
  • peek/front: view the element at the front of the queue without removing it.
  • is_empty: check if the queue is empty.
  • size: get the current number of elements.

Implementations in Python:

  • list: Simple, but inefficient for frequent pop(0) operations (shifting elements).
  • collections.deque: Double-ended queue optimized for adding/removing from both ends, effectively used as a regular queue.
  • queue.Queue: Thread-safe implementation, convenient for data exchange between threads.

Examples of using collections.deque:

# Initialize queue
from collections import deque
q = deque()

# Add elements (enqueue)
q.append('a')
q.append('b')
q.append('c')

# Remove and return elements (dequeue)
first_element = q.popleft() # 'a'
second_element = q.popleft() # 'b'

# View the element at the front (peek) - indirect, requires importing the function or checking if not empty
if q:
    peek_element = q[0] # 'c'

# Check if empty
is_empty = not q

# Size
current_size = len(q)

Examples of using queue.Queue:

# Initialize thread-safe queue
from queue import Queue
q_threaded = Queue()

# Add elements (put)
q_threaded.put('task1')
q_threaded.put('task2')

# Remove and return elements (get) - blocking operation by default
task = q_threaded.get() # 'task1'

# Notify task completion (for join)
q_threaded.task_done()

# Check if empty
is_empty_threaded = q_threaded.empty()

# Size
current_size_threaded = q_threaded.qsize()

Used in tasks such as:

  • Task scheduling.
  • FIFO buffers.
  • Graph traversal algorithms (BFS - Breadth-First Search).
  • Request processing (e.g., in web servers).
  • Thread-safe interaction between threads (with queue.Queue).