PYTHON
Implement a First-In, First-Out (FIFO) Queue with Python Lists
Discover how to implement a simple queue data structure in Python using a list, illustrating enqueue and dequeue operations for managing data in a FIFO order.
class Queue:
def __init__(self):
self._items = []
def enqueue(self, item):
"""Adds an item to the back of the queue."""
self._items.append(item)
def dequeue(self):
"""Removes and returns the item from the front of the queue."""
if not self.is_empty():
return self._items.pop(0) # pop(0) removes the first item
raise IndexError("dequeue from empty queue")
def peek(self):
"""Returns the item at the front of the queue without removing it."""
if not self.is_empty():
return self._items[0]
raise IndexError("peek from empty queue")
def is_empty(self):
"""Checks if the queue is empty."""
return len(self._items) == 0
def size(self):
"""Returns the number of items in the queue."""
return len(self._items)
def __str__(self):
return str(self._items)
# Example Usage:
my_queue = Queue()
my_queue.enqueue('Customer A')
my_queue.enqueue('Customer B')
my_queue.enqueue('Customer C')
print(f"Queue after enqueues: {my_queue}") # Expected: ['Customer A', 'Customer B', 'Customer C']
print(f"Front item (peek): {my_queue.peek()}") # Expected: Customer A
print(f"Dequeued item: {my_queue.dequeue()}") # Expected: Customer A
print(f"Queue after dequeue: {my_queue}") # Expected: ['Customer B', 'Customer C']
print(f"Is queue empty? {my_queue.is_empty()}") # Expected: False
my_queue.dequeue()
my_queue.dequeue()
print(f"Is queue empty? {my_queue.is_empty()}") # Expected: True
How it works: This snippet illustrates building a simple First-In, First-Out (FIFO) queue using Python lists. The `enqueue` method adds items to the end of the list with `append()`. The `dequeue` method removes and returns items from the beginning of the list using `pop(0)`. While effective, `pop(0)` can be inefficient for very large queues as it shifts all subsequent elements. For performance-critical applications with large queues, `collections.deque` is a more optimized choice, but this list-based approach is simple and clear for basic use.