Stack#
The stack is a very simple data structure. It is a list with one restrictions. 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.
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):
ws = []
for i, item in enumerate(self.items[::-1]):
if i == 0 : ws.append(f"{item} <first")
elif i == len(self.items)-1: ws.append(f"{item} <last")
else : ws.append(str(item))
return "\n".join(ws)
def push(self, value):
if len(self.items) == MAXIMUM_STACK_SIZE-1: raise Exception("Stack overflow")
self.items.append(value)
def pop(self, n=-1):
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 <first
4
2 <last
We pop one of the stack. Which is 1
.
stack.pop()
Now only 2 values are left on the stack. Notice how we removed 1
. And 4
has become the first value.
print(stack)
4 <first
2 <last