Using Python List as Stack

Stacks are a fundamental data structure used in computer science. They follow the Last-In-First-Out (LIFO) principle, meaning the last element added to the stack is the first one to be removed. In this blog, we’ll explore how using python list as stack can be easily implemented.

Table of Contents

What is a Stack?

A stack is a collection of elements with two main operations:

  1. Push: Adds an element to the top of the stack.
  2. Pop: Removes the top element from the stack.

A real-world analogy for a stack is a stack of plates. You add plates to the top and remove them from the top.

Python List as Stack

Python’s built-in list type can be used to create a stack. Here’s how:

Pushing Elements onto the Stack

To add an element to the stack (i.e., push), you can use the append method.

stack = []
stack.append(5)
stack.append(10)
print(stack)  # Output: [5, 10]

Popping Elements from the Stack

To remove an element from the stack (i.e., pop), you can use the pop method without any arguments.

top_element = stack.pop()
print(top_element)  # Output: 10
print(stack)        # Output: [5]

Checking If the Stack Is Empty

You can check if the stack is empty by using the len function.

if len(stack) == 0:
    print("Stack is empty")
else:
    print("Stack is not empty")

Peek at the Top Element

To peek at the top element without removing it, you can simply access the last element using indexing.

top_element = stack[-1]
print(top_element)  # Output: 5
https://codeblockhub.com/python/python-quiz/python-quiz-python-list-01/
https://codeblockhub.com/python/python-quiz/python-quiz-python-list-02/
https://codeblockhub.com/python/python-quiz/python-quiz-python-list-03/

Summary

Python lists provide a simple and efficient way to implement a stack. By using the built-in append and pop methods, you can create a stack and perform all the typical stack operations. Here’s a quick recap:

  • Push: Use append to add elements to the stack.
  • Pop: Use pop to remove the top element from the stack.
  • Peek: Use [-1] to look at the top element without removing it.
  • Check if empty: Use len(stack) == 0 to check if the stack is empty.

Python lists make working with stacks incredibly straightforward, allowing you to focus on the logic of your code without worrying about implementing the underlying data structure.