In this tutorial you will learn how to create a stack-like list class that can contain only a certain number of elements, any additional elements pushed to this list that cause it to exceed the limit will result in the elements at the tail of the stack being removed.
Creating our stack-like list object
The built-in list type in python can be used as a stack using the append() and pop() functions, the only additional functionality we would want to add on top is to have a maximum capacity to this list, so the easiest way to go about this would be to simply extend the built-in list class.
class MaxStack(list):
def __init__(self, max_size):
super().__init__()
self.max_size = max_size
# Simply here to adhere more to a stack
def push(self, element):
self.append(element)
def append(self, element):
super().append(element)
# If the list has now exceeded the maximum size, remove the element at the tail of the list
if super().__len__() > self.max_size:
super().__delitem__(0)
In the above code we are overriding the constructor to allow for a max_size argument, and the append method to handle the logic for removing excess elements. We also add a push method for this class to behave more like a stack (even though it acts only as an alias to append)
Using the list and exceeding the maximum number of elements
This object will behave much like a regular python list, simply instantiate it with the maximum number of desired elements, then you can start using it just like a normal list, however in this example we'll use our push() alias method
my_list = MaxStack(3)
my_list.push(1) # my_list = [1]
my_list.push(2) # my_list = [1, 2]
my_list.push(3) # my_list = [1, 2, 3]
my_list.push(4) # my_list = [2, 3, 4]
my_list.push(5) # my_list = [3, 4, 5]
list_head = my_list.pop() # my_list = [3, 4]
As you can see, you can append to this list normally until the limit is exceeded at which point the list will start trimming itself from the tail.
The pop() function still works as expected and will remove and return the element from the head of the list.