Stack#

The stack is a very simple data structure. It is a list with one restrctions. You can only directly interact with the top of it.

You can push a new value to the top of the stack or you can pop an already existing value from the stack.

A stack of plates is a good metaphor. You can add a plate or remove a plate from the top. A stack works in the exact same way.

title

The EVM stack has a maximum capacity of 1024 items. Every item on the stack is at max a 256 bit value (32 bytes).

MAXIMUM_STACK_SIZE = 1024

We also throw an exception if we try to pop a value of a stack that is empty.

class Stack:
    def __init__(self): self.items = []
    def __str__ (self): return "\n".join(map(str, self.items[::-1]))
        
    def push(self, value): 
        if len(self.items) == MAXIMUM_STACK_SIZE-1: raise Exception("Stack overflow")
        self.items.append(value)    
        
    def pop (self): 
        if len(self.items) == 0: raise Exception("Stack underflow")
        return self.items.pop()
    
    def pop(self, n):
        if len(self.items) < n: raise Exception("Stack overflow")
        del self.items[n]

We create a Stack

stack = Stack()

We push 3 values to the stack

stack.push(2)
stack.push(4)
stack.push(1)

print(stack)
1
4
2

We pop one of the stack

print(stack.pop())
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[5], line 1
----> 1 print(stack.pop())

TypeError: pop() missing 1 required positional argument: 'n'

Now only 3 values are left on the stack

print(stack)
4
2