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
In [1]:
from collections import deque
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)
In [3]:
# Append an item to the right
queue.append('A')
# View queue
queue
Out[3]:
In [4]:
# Append an item to the left
queue.appendleft('A')
# View queue
queue
Out[4]:
In [5]:
# Count occurances of item
queue.count('A')
# View queue
queue
Out[5]:
In [6]:
# Remove and return right-most item
queue.pop()
# View queue
queue
Out[6]:
In [7]:
# Remove and return left-most item
queue.popleft()
# View queue
queue
Out[7]:
In [8]:
# Insert item to the right of an item
queue.insert(2, 'A')
# View queue
queue
Out[8]:
In [9]:
# Reverse the queue
queue.reverse()
# View queue
queue
Out[9]:
In [10]:
# Delete all items
queue.clear()
# View queue
queue
Out[10]: