Python Stacks and Queues

In Python, lists can be used as stacks and queues. Stacks are like a box of pringles; the last chip to be placed inside the box is the first one to be taken out. This is called Last In First Out (LIFO). A queue is like the line up at the bus stop. The first person to get in the line is the first person to get on the bus. This is called First In First Out (FIFO).

Python Stacks

# list a is the stack
a = [1,2,3]
a.append(4)
print a
print a.pop()		# 4
print a.pop()		# 3

Python Queues

from collections import deque
queue = deque([1,2,3])
queue.append(4)					# deque([1,2,3,4])
queue.append(5)					# deque([1,2,3,4,5])
print queue.popleft()			# 1
print queue						# deque([2,3,4,5])