I am having trouble understanding how the deque works in the snippet of code below, while trying to recreate a queue and a stack in Python.
Stack Example - Understood
stack = ["a", "b", "c"]
# push operation
stack.append("e")
print(stack)
# pop operation
stack.pop()
print(stack)
As expected when pushing and popping, the "e" goes Last In, First Out (LIFO). My question is with the example below.
Queue Example - Not Understanding
from collections import deque
dq = deque(['a','b','c'])
print(dq)
# push
dq.append('e')
print(dq)
# pop
dq.pop()
print(dq)
When pushing and popping, the "e" goes Last In, First Out (LIFO). Shouldn't it be First In, First Out (FIFO)?
A deque is a generalization of stack and a queue (It is short for "double-ended queue").
Thus, the pop() operation still causes it to act like a stack, just as it would have as a list. To make it act like a queue, use the popleft() command. Deques are made to support both behaviors, and this way the pop() function is consistent across data structures. In order to make the deque act like a queue, you must use the functions that correspond to queues. So, replace pop() with popleft() in your second example, and you should see the FIFO behavior that you expect.
Deques also support a max length, which means when you add objects to the deque greater than the maxlength, it will "drop" a number of objects off the opposite end to maintain its max size.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With