In this article we will look at how we can implement a fixed-length stack in Python.
A stack is a data structure that observes the Last In First Out(LIFO) principle. This is where the last item to be inserted is the first one to be removed.
In some cases, it may be necessary to have a stack that is of fixed-length. Fixed-length stacks have a predetermined maximum number of elements that they can hold.
There are two types of fixed-length stacks.The first type raises an error on an attempt to add an element when the maximum capacity is reached, the other type discards the oldest item to accommodate the incoming one.
A list-based Fixed-length stack
In this section we will implement a FixedStack
class using a list for internal storage of the stack elements.
The class have the following methods:
push(e) |
Adds element e at the top of the stack. Raises an error if the stack is full. |
pop() |
Removes and returns the top element. Raises an exception if the stack is empty. |
top() |
Returns the top element without removing it. Raises an exception if the stack is empty. |
is_empty() |
Checks whether the stack is empty. Returns True if so, False otherwise. |
is_full() |
Checks whether the stack is full. Returns True if so, False otherwise. |
Fixed-length stack using collections.deque
The deque
class in the collections
module has efficient methods for adding and removing elements from both ends. We can use a deque
object as a stack by appending and popping from just one end, either the rear or the front of the deque
.
The fixed-length property can be achieved by setting the maxlen
parameter when instantiating the deque
.
We can use append()
and pop()
methods to perform push and pop operations from the rear end of the deque
object.
Note: A deque does not raise an error if full. It instead removes the oldest item to create room for the incoming item. This ensures that the maximum capacity is never exceeded and that there is always space for new items to be added.
As shown above, when the maxlen
parameter is set and the deque
is full, appending an element makes the oldest element to be discarded to create room for the incoming element.