FIFO, LIFO Queues using Deque

In Python, Deques are a generalization of Stacks (Last In First Out) and Queues ( Last In First Out, First In First Out) data structures. Deque stands for “double-ended queue”. Deques support thread-safe, memory efficient appends and pops from either side of the deque with approximately the same O(1) performance in either direction.

List as Stack (LIFO)

stack = ["a", "b", "c"]

# add an element to the end of the list
stack.append("e")
stack.append("f")
print stack

# pop operation
stack.pop()
print stack

# pop operation
stack.pop()
print stack

# push operation
stack.append("d")
print stack

Lists as Queues (LIFO & FIFO)

from collections import deque

dq = deque(['b','c','d'])
print dq

# adding an element to the right of the queue
dq.append('e')
print dq

# adding an element to the left of the queue
dq.appendleft('a')
print dq

# iterate over deque's elements
for elt in dq:
    print(elt)

# pop out an element at from the right of the queue
dq.pop()
print dq

# pop out an element at from the right of the queue
dq.popleft()
print dq

# print as list
print list(dq)

# reversed list
print list(reversed(dq))

# empty the deque element
dq.clear()

Download

Download From Github