Quick actions

cmd+k|ctrl+k

Navigation

Languages

stack

Snippet info

Language

Python

Visibility

public

Author

mammal

Created

2025-03-17T01:11:14.834205Z

Updated

2025-03-17T01:12:51.72749Z

class Stack:
    def __init__(self):
        self.items = []

    def is_empty(self):
        return len(self.items) == 0

    def push(self, item):
        self.items.append(item)

    def pop(self):
        if not self.is_empty():
            return self.items.pop()
        else:
            return "Stack is empty"

    def peek(self):
        if not self.is_empty():
            return self.items[-1]
        else:
            return "Stack is empty"

    def size(self):
        return len(self.items)

# Example usage
stack = Stack()

print("Is the stack empty?", stack.is_empty())  # True

stack.push(1)
stack.push(2)
stack.push(3)

print("Stack size:", stack.size())  # 3
print("Top item:", stack.peek())    # 3

print("Popped item:", stack.pop())  # 3
print("New top item:", stack.peek())  # 2

print("Stack size after pop:", stack.size())  # 2
INFO