Title: Queues And Stacks
Slug: queues_and_stacks
Summary: Queues And Stacks in Python.
Date: 2016-01-23 12:00
Category: Python
Tags: Basics
Authors: Chris Albon

Interesting in learning more? Check out Fluent Python

Preliminaries


In [1]:
from collections import deque

Make A Queue


In [2]:
# Option 1: Make a queue
queue = deque(range(10))

# Option 2: Make a queue that, if full, discards any item at the 
# opposite end to where you added an item.
queue = deque(range(10), maxlen=10)

Manipulate Queue


In [3]:
# Append an item to the right

queue.append('A')

# View queue
queue


Out[3]:
deque([1, 2, 3, 4, 5, 6, 7, 8, 9, 'A'])

In [4]:
# Append an item to the left

queue.appendleft('A')

# View queue
queue


Out[4]:
deque(['A', 1, 2, 3, 4, 5, 6, 7, 8, 9])

In [5]:
# Count occurances of item
queue.count('A')

# View queue
queue


Out[5]:
deque(['A', 1, 2, 3, 4, 5, 6, 7, 8, 9])

In [6]:
# Remove and return right-most item
queue.pop()

# View queue
queue


Out[6]:
deque(['A', 1, 2, 3, 4, 5, 6, 7, 8])

In [7]:
# Remove and return left-most item
queue.popleft()


# View queue
queue


Out[7]:
deque([1, 2, 3, 4, 5, 6, 7, 8])

In [8]:
# Insert item to the right of an item
queue.insert(2, 'A')

# View queue
queue


Out[8]:
deque([1, 2, 'A', 3, 4, 5, 6, 7, 8])

In [9]:
# Reverse the queue
queue.reverse()

# View queue
queue


Out[9]:
deque([8, 7, 6, 5, 4, 3, 'A', 2, 1])

In [10]:
# Delete all items
queue.clear()

# View queue
queue


Out[10]:
deque([])