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 Python lists can be easily used to implement a stack.
What is a Stack?
A stack is a collection of elements with two main operations:
- Push: Adds an element to the top of the stack.
- 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.
Using Python Lists as Stacks
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
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.