🚀 Day 12: Deque Data Structure in Python (Code Examples) 🚀
#DataStructures #Python #DSA #CodeExamples #TechLearning
Here’s a practical example of using collections.deque in Python, complete with docstrings and comments to clarify each operation. This will help you understand how to leverage deques for efficient front/back operations.
Example: Deque Operations with Comments & Docstrings
from collections import deque
def deque_operations():
"""
Demonstrates key operations of a deque (Double-Ended Queue).
- Appends and pops from both ends.
- Rotates elements.
- Uses maxlen to limit size.
"""
# Initialize a deque with a max length of 5
dq = deque([1, 2, 3], maxlen=5)
print("Initial deque:", dq) # Output: deque([1, 2, 3])
# Append to the right (rear)
dq.append(4)
print("After append(4):", dq) # Output: deque([1, 2, 3, 4])
# Append to the left (front)
dq.appendleft(0)
print("After appendleft(0):", dq) # Output: deque([0, 1, 2, 3, 4])
# Pop from the right
right_pop = dq.pop()
print("After pop():", dq, "Popped:", right_pop) # Output: deque([0, 1, 2, 3]), Popped: 4
# Pop from the left
left_pop = dq.popleft()
print("After popleft():", dq, "Popped:", left_pop) # Output: deque([1, 2, 3]), Popped: 0
# Extend the deque with multiple elements (right side)
dq.extend([4, 5])
print("After extend([4,5]):", dq) # Output: deque([1, 2, 3, 4, 5])
# Extend to the left
dq.extendleft([-1, -2])
print("After extendleft([-1,-2]):", dq) # Output: deque([-2, -1, 1, 2, 3, 4, 5])
# Rotate elements (positive: right, negative: left)
dq.rotate(2) # Rotate right by 2 positions
print("After rotate(2):", dq) # Output: deque([4, 5, -2, -1, 1, 2, 3])
dq.rotate(-3) # Rotate left by 3 positions
print("After rotate(-3):", dq) # Output: deque([1, 2, 3, 4, 5, -2, -1])
# Peek at front and rear elements
print("Front element:", dq[0]) # Output: 1
print("Rear element:", dq[-1]) # Output: -1
# Check if deque is empty
print("Is deque empty?", len(dq) == 0) # Output: False
if __name__ == "__main__":
deque_operations()
Key Takeaways from the Code
maxlen: Limits the size of the deque. If the deque exceeds maxlen, the oldest elements are automatically removed.
append() / appendleft(): Add elements to the right or left end.
pop() / popleft(): Remove elements from the right or left end.
- / : Add multiple elements to the right or left.