Implement a simple Stack class in Python

Document 对象参考手册Python3 Examples

A Stack is a data structure that follows the Last-In-First-Out (LIFO) principle. We can use Python's list to implement a simple Stack class. This class will include the following basic operations:

  1. push(item): Push the elementitemonto the top of the stack.
  2. pop(): Remove and return the element at the top of the stack.
  3. peek(): Return the element at the top of the stack without removing it.
  4. is_empty(): Check whether the stack is empty.
  5. size(): Return the number of elements in the stack.

Example

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

    def is_empty(self):
        return self.items == []

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

    def pop(self):
        if self.is_empty():
            raise IndexError("pop from empty stack")
        return self.items.pop()

    def peek(self):
        if self.is_empty():
            raise IndexError("peek from empty stack")
        return self.items[-1]

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

Code analysis:

  1. __init__(self): Initialize an empty listitemsto store the elements in the stack.
  2. is_empty(self): Check whether the stack is empty; ifitemsthe list is empty, returnTrue, otherwise returnFalse。
  3. push(self, item): Add the elementitemto theitemsend of the list, i.e., push it onto the top of the stack.
  4. pop(self): Remove and returnitemsthe last element of the list, i.e., the top element of the stack. If the stack is empty, raiseIndexErrorexception.
  5. peek(self): Returnitemsthe last element of the list, i.e., the top element of the stack, without removing it. If the stack is empty, raiseIndexErrorexception.
  6. size(self): Returnitemsthe length of the list, i.e., the number of elements in the stack.

Output result:

Example

# Example usage
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
print(stack.peek())  # Output: 3
print(stack.pop())   # Output: 3
print(stack.size())  # Output: 2
print(stack.is_empty())  # Output: False
stack.pop()
stack.pop()
print(stack.is_empty())  # Output: True

In this example, we first create a stack objectstack, then push the elements one by one1、2and3onto the stack.3), and remove it. Finally, we check the size of the stack and whether it is empty.

Document 对象参考手册Python3 Examples

Other extensions