Code Explanation:
1. Importing deque
from collections import deque
The deque (double-ended queue) is imported from the collections module.
A deque is like a list but optimized for fast appending and popping from both ends.
2. Creating a deque
dq = deque([1, 2, 3])
A new deque is created with elements [1, 2, 3].
Current dq = deque([1, 2, 3]).
3. Adding element to the left
dq.appendleft(0)
appendleft(0) inserts 0 at the left end of the deque.
Now dq = deque([0, 1, 2, 3]).
4. Adding element to the right
dq.append(4)
append(4) inserts 4 at the right end of the deque.
Now dq = deque([0, 1, 2, 3, 4]).
5. Printing deque as list
print(list(dq))
Converts the deque into a list using list(dq) for easy printing.
Output:
[0, 1, 2, 3, 4]
Final Output:
[0, 1, 2, 3, 4]


0 Comments:
Post a Comment