Stack data structure implementation with Python

PHOTO EMBED

Tue Jun 18 2024 03:26:20 GMT+0000 (Coordinated Universal Time)

Saved by @pynerds #python

#an exception to be raised by an empty stack
class EmptyStack(Exception):
    pass

class Stack:
    
    def __init__(self):
        self._items = [] #non-public list for storing stack elements

    def __len__(self):
        return len(self._items)

    def isEmpty(self):
        return len(self) == 0 

    def push(self, e):
        self._items.append(e) #add the element at the end of the list

    def top(self):
        if self.isEmpty():
            raise EmptyStack("Stack Is Empty.")
        return self._items[-1] #Return the last element in list

    def pop(self):
        if self.isEmpty():
            raise EmptyStack("Stack Is Empty.")
        return self._items.pop() #pop the last item from the list

# test the stack
S = Stack()

S.push("A")
S.push("B")
S.push("C")
print(S.pop())
print(S.pop())
print(S.pop())
print(S.pop())
content_copyCOPY

https://www.pynerds.com/data-structures/implement-stack-data-structure-in-python/