Code Explanation:
๐น 1. Importing deque
from collections import deque
✅ Explanation:
deque stands for Double Ended Queue.
It is available in Python's collections module.
It allows insertion and deletion from both the left and right ends efficiently.
Visual representation:
Left End Right End
← [ deque ] →
๐น 2. Creating a Deque
d = deque([10, 20, 30])
✅ Explanation:
A deque object is created with three elements.
Current deque:
deque([10, 20, 30])
Visual:
Left Right
10 ← 20 ← 30
Current state:
d
↓
[10, 20, 30]
๐น 3. Using appendleft()
d.appendleft(5)
✅ Explanation:
appendleft() inserts a new element at the beginning (left side) of the deque.
Before:
[10, 20, 30]
Insert:
5
After:
[5, 10, 20, 30]
Visual:
Left
5 ← 10 ← 20 ← 30
Right
Current state:
d
↓
[5, 10, 20, 30]
๐น 4. Using append()
d.append(40)
✅ Explanation:
append() adds a new element at the end (right side) of the deque.
Before:
[5, 10, 20, 30]
Insert:
40
After:
[5, 10, 20, 30, 40]
Visual:
Left
5 ← 10 ← 20 ← 30 ← 40
Right
Current state:
d
↓
[5, 10, 20, 30, 40]
๐น 5. Using pop()
d.pop()
✅ Explanation:
pop() removes the last (rightmost) element from the deque.
Current deque:
[5, 10, 20, 30, 40]
Removed element:
40
Remaining deque:
[5, 10, 20, 30]
Visual:
Before
5 ← 10 ← 20 ← 30 ← 40
❌ Remove
After
5 ← 10 ← 20 ← 30
๐น 6. Final Deque State
After all operations:
deque([5, 10, 20, 30])
Current state:
d
↓
[5, 10, 20, 30]
๐น 7. Converting Deque to List
list(d)
✅ Explanation:
list() converts the deque into a normal Python list.
Before:
deque([5, 10, 20, 30])
After:
[5, 10, 20, 30]
๐น 8. Printing the Result
print(list(d))
✅ Explanation:
Prints the final list.
Output:
[5, 10, 20, 30]
๐ฏ Final Output
[5, 10, 20, 30]

0 Comments:
Post a Comment