Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Does Deque Work in Python

Tags:

python

queue

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)?

like image 602
Victor Rodriguez Avatar asked Jul 31 '16 01:07

Victor Rodriguez


Video Answer


1 Answers

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.

like image 188
James Avatar answered Sep 27 '22 19:09

James