Code Explanation:
Import deque from collections
from collections import deque
deque is a special data structure from the collections module.
It stands for Double Ended Queue, meaning you can add or remove items from both left and right ends efficiently.
Create a deque
dq = deque([10, 20, 30])
A deque named dq is created with initial elements 10, 20, 30.
The structure now looks like: [10, 20, 30]
Append an Element to the Right Side
dq.append(40)
append(40) adds 40 to the right end of the deque.
Now the deque becomes: [10, 20, 30, 40]
Append an Element to the Left Side
dq.appendleft(5)
appendleft(5) adds 5 to the left end.
Now the deque becomes: [5, 10, 20, 30, 40]
Print First and Last Elements
print(dq[0], dq[-1])
dq[0] → first element = 5
dq[-1] → last element = 40
Output:
5 40
Final Output
5 40
.png)

0 Comments:
Post a Comment