Python Tutorial: Stacks 🎯

beginner
8 min

Python Tutorial: Stacks 🎯

Stacks are a type of data structure that follows the LIFO (Last In, First Out) principle. In Python, stacks can be implemented using lists. Let's dive into the world of stacks and learn how to use them effectively!

Introduction to Stacks 📝

A stack is a collection of items where items are added and removed only from the top. It's like a pile of books where you can only add a book on top of the existing pile or remove the topmost book.

In Python, you can create a stack using a list. The append() function is used to add an item at the end (top) of the stack, and the pop() function is used to remove the top item from the stack.

python
# Creating an empty stack my_stack = [] # Adding items to the stack my_stack.append("Python") my_stack.append("Java") my_stack.append("C++") print("My Stack:", my_stack)

Output:

My Stack: ['Python', 'Java', 'C++']

Basic Stack Operations 💡

1. Push (Add an item to the stack)

To add an item to the stack, use the append() function.

python
my_stack.append("C") print("My Stack after push:", my_stack)

Output:

My Stack after push: ['Python', 'Java', 'C++', 'C']

2. Pop (Remove an item from the stack)

To remove the top item from the stack, use the pop() function.

python
top_item = my_stack.pop() print("Top item removed from the stack:", top_item) print("My Stack after pop:", my_stack)

Output:

Top item removed from the stack: C My Stack after pop: ['Python', 'Java', 'C++']

3. Peek (Check the top item of the stack without removing it)

To check the top item of the stack without removing it, use the -1 index.

python
top_item = my_stack[-1] print("Top item without removing it:", top_item)

Output:

Top item without removing it: C++

4. Check if the stack is empty

To check if the stack is empty, use the len() function or if my_stack:.

python
if not my_stack: print("The stack is empty.")

Output:

The stack is empty.

Advanced Stack Operations ✅

1. Reverse a list using a stack

To reverse a list using a stack, first, append the list items to the stack, then pop them and store them in a new list.

python
my_list = ["A", "B", "C", "D"] my_stack = [] for item in my_list: my_stack.append(item) reversed_list = [] while my_stack: reversed_list.append(my_stack.pop()) print("Original List:", my_list) print("Reversed List:", reversed_list)

Output:

Original List: ['A', 'B', 'C', 'D'] Reversed List: ['D', 'C', 'B', 'A']

2. Check if a string is a valid parenthesis sequence

A string is a valid parenthesis sequence if the number of opening parentheses is equal to the number of closing parentheses. We can use a stack to check this.

python
def is_valid_parenthesis(sequence): stack = [] opening_parentheses = ['(', '[', '{'] closing_parentheses = [')', ']', '}'] for parenthesis in sequence: if parenthesis in opening_parentheses: stack.append(parenthesis) elif parenthesis in closing_parentheses: if not stack or stack.pop() != get_matching_parenthesis(parenthesis): return False return not stack def get_matching_parenthesis(parenthesis): if parenthesis == '(': return ')' elif parenthesis == '[': return ']' elif parenthesis == '{': return '}'
Quick Quiz
Question 1 of 1

What is a stack in Python?

Quick Quiz
Question 1 of 1

How to add an item to a stack in Python?

Quick Quiz
Question 1 of 1

How to remove the top item from a stack in Python?

Quick Quiz
Question 1 of 1

How to check the top item of a stack without removing it in Python?

Quick Quiz
Question 1 of 1

What is the time complexity of appending an item to a stack in Python?

Quick Quiz
Question 1 of 1

What is the time complexity of removing an item from a stack in Python?