Stack Implementation in Python

1. Stack Data Structure Overview

A stack is an ordered list in which insertion and deletion are done at one end, called a top. The last element inserted is the first one to be deleted. Hence, it is called the Last in First Out (LIFO) or First in Last Out (FILO) list.

Main stack operations

Push Operation:
The process of putting a new data element onto the stack is known as a Push Operation.

Pop Operation:
Accessing the content while removing it from the stack, is known as a Pop Operation.

Other stack operations:

  • int peek(): Returns the top-most element of the stack
  • int size(): Returns the number of elements stored in the stack.
  • int isEmpty(): Indicates whether any elements are stored in the stack or not.

2. Implementation Steps

1. Create an empty list to represent the stack.

2. Define the push method to add an element to the top of the stack.

3. Define the pop method to remove the top element from the stack.

4. Define the peek method to view the top element without removing it.

5. Implement auxiliary methods like is_empty to check if the stack is empty and size to get the number of elements in the stack.

3. Implementation in Python

class Stack:
    def __init__(self):
        # Initialize an empty stack
        self.items = []
    def push(self, item):
        # Add an item to the top of the stack
        self.items.append(item)
    def pop(self):
        # Remove and return the top item from the stack
        if not self.is_empty():
            return self.items.pop()
        return None
    def peek(self):
        # Return the top item from the stack without removing it
        if not self.is_empty():
            return self.items[-1]
        return None
    def is_empty(self):
        # Check if the stack is empty
        return len(self.items) == 0
    def size(self):
        # Return the number of items in the stack
        return len(self.items)
# Test the Stack class
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
print("Top item:", stack.peek())  # Should print 3
print("Stack size:", stack.size())  # Should print 3

Output:

Top item: 3
Stack size: 3

Explanation:

1. We start by initializing an empty list items to represent our stack.

2. The push method appends an item to the end of the list, which is the top of the stack.

3. The pop method checks if the stack is not empty, and if so, removes and returns the last item from the list.

4. The peek method returns the last item from the list without removing it.

5. The is_empty method checks if the stack is empty by seeing if the length of items is 0.

6. The size method returns the number of items currently in the stack.

Related Data Structures in Python


Comments