Introduction
Imagine you need a line where people can join or leave from both the front and the back easily. A deque solves this problem by letting you add or remove items from both ends quickly.
Imagine a train platform where passengers can board or leave from either the front or the back of the train. This flexibility helps manage crowds efficiently depending on where the train stops.
┌───────────────┐ │ Deque │ ├───────────────┤ │ Front [ ] │ │ [ ] │ │ [ ] │ │ Back [ ] │ └───────────────┘ ← push front / pop front push back / pop back →
from collections import deque # Create a deque dq = deque() # Add elements to both ends dq.append('back') # push back dq.appendleft('front') # push front print('Deque after additions:', list(dq)) # Remove elements from both ends front_item = dq.popleft() # pop front back_item = dq.pop() # pop back print('Removed from front:', front_item) print('Removed from back:', back_item) print('Deque now:', list(dq))