Code Explanation:
1. Import deque
from collections import deque
Imports deque (double-ended queue) from the collections module.
deque allows fast appends and pops from both ends (left and right).
2. Create deque
dq = deque([10, 20, 30])
Creates a deque with elements [10, 20, 30].
Now:
dq → [10, 20, 30]
3. Append to the left
dq.appendleft(5)
Adds 5 to the left end of the deque.
Now:
dq → [5, 10, 20, 30]
4. Append to the right
dq.append(40)
Adds 40 to the right end of the deque.
Now:
dq → [5, 10, 20, 30, 40]
5. Remove from the left
dq.popleft()
Removes the first element (5) from the left.
Now:
dq → [10, 20, 30, 40]
6. Remove from the right
dq.pop()
Removes the last element (40) from the right.
Now:
dq → [10, 20, 30]
7. Print deque as list
print(list(dq))
Converts the deque to a list for easy display.
Output:
[10, 20, 30]
Final Output:
[10, 20, 30]


0 Comments:
Post a Comment