Code Explanation:
Importing the deque class
from collections import deque
The deque (pronounced deck) is imported from Python’s built-in collections module.
It stands for double-ended queue, which allows fast appends and pops from both ends (left and right).
Much faster than normal lists when you modify both ends frequently.
Creating a deque with initial elements
dq = deque([1, 2, 3])
A deque named dq is created containing [1, 2, 3].
Initially, the deque looks like this:
deque([1, 2, 3])
Adding element to the left side
dq.appendleft(0)
The method .appendleft() inserts an element at the beginning of the deque.
Now the deque becomes:
deque([0, 1, 2, 3])
Adding element to the right side
dq.append(4)
The .append() method adds an element to the right end (like normal list append).
Now the deque looks like:
deque([0, 1, 2, 3, 4])
Removing element from the right side
dq.pop()
.pop() removes the last (rightmost) element.
It removes 4.
The deque now becomes:
deque([0, 1, 2, 3])
Removing element from the left side
dq.popleft()
.popleft() removes the first (leftmost) element.
It removes 0.
The deque now becomes:
deque([1, 2, 3])
Printing the final deque
print(list(dq))
Converts the deque into a list and prints it.
Output is:
[1, 2, 3]
Final Output
[1, 2, 3]


0 Comments:
Post a Comment