Code Explanation:
1. Importing deque
from collections import deque
deque (double-ended queue) comes from Python’s collections module.
It is like a list but optimized for fast appends and pops from both left and right.
2. Creating a deque
dq = deque([1, 2, 3])
Initializes a deque with elements [1, 2, 3].
Current state of dq:
deque([1, 2, 3])
3. Adding to the Left
dq.appendleft(0)
.appendleft(value) inserts a value at the beginning (left side).
After this line, dq becomes:
deque([0, 1, 2, 3])
4. Adding to the Right
dq.append(4)
.append(value) inserts a value at the end (right side).
After this line, dq becomes:
deque([0, 1, 2, 3, 4])
5. Converting to List & Printing
print(list(dq))
list(dq) converts the deque into a regular list.
Output will be:
[0, 1, 2, 3, 4]
Final Output
[0, 1, 2, 3, 4]
.png)

0 Comments:
Post a Comment