Deque Operations

Double-Ended Queue - Append and pop on both ends

Visual Workspace

Size: 0
Left End / Rear (appendleft / popleft)
Right End / Front (append / pop)
Deque is currently empty

Controls

Performance Advantage

A deque (double-ended queue) is much faster than a standard list for adding and removing elements from ends. Deque is O(1) vs list is O(n) for these specific operations.

# Initialize deque visualizer...

Python Deque Methods

In Python, you can utilize a deque by importing it from the built-in collections module.

  • append(x) Insert to the right end
  • appendleft(x) Insert to the left end
  • pop() Delete from the right end
  • popleft() Delete from the left end
  • index(e, b, end) Return first index of value
  • insert(i, a) Insert value (a) at index (i)
  • remove() Remove first occurrence
  • count() Count occurrences of value
View python_deque_demo.py
from collections import deque

# Initialize a deque with some values
d = deque([10, 15, 20, 30])
print(f"Initial: {d}")

# Add elements to the Right (Rear in memory, Front in visual queue concept)
d.append(40)
print(f"After append(40): {d}")

# Add elements to the Left (Front in memory, Rear in visual queue concept)
d.appendleft(5)
print(f"After appendleft(5): {d}")

# Remove element from the Right
popped_right = d.pop()
print(f"Popped from right: {popped_right}")

# Remove element from the Left
popped_left = d.popleft()
print(f"Popped from left: {popped_left}")

# Extra Operations
d.insert(2, 99)
print(f"After insert(2, 99): {d}")

print(f"Count of 20: {d.count(20)}")