0
0
DSA Pythonprogramming~15 mins

Peek Top Element of Stack in DSA Python - Build from Scratch

Choose your learning style9 modes available
Peek Top Element of Stack
📖 Scenario: You are managing a stack of books. You want to see which book is currently on the top without removing it.
🎯 Goal: Build a simple stack using a list and write code to peek (look at) the top element of the stack.
📋 What You'll Learn
Create a list called stack with exact elements 'Math', 'Science', 'History'
Create a variable called top_index to hold the index of the top element
Use top_index to get the top element from stack and store it in top_element
Print the value of top_element
💡 Why This Matters
🌍 Real World
Stacks are used in many places like undo features in apps, browser history, and managing tasks in order.
💼 Career
Understanding stacks helps in software development roles where managing data order and temporary storage is needed.
Progress0 / 4 steps
1
Create the stack
Create a list called stack with these exact elements in order: 'Math', 'Science', 'History'
DSA Python
Hint

Use square brackets [] to create a list and separate elements with commas.

2
Find the top index
Create a variable called top_index and set it to the index of the last element in stack using len(stack) - 1
DSA Python
Hint

The last element's index is always the length of the list minus one.

3
Peek the top element
Create a variable called top_element and set it to the element at top_index in stack
DSA Python
Hint

Use square brackets with the index to get an element from a list.

4
Print the top element
Print the value of top_element to show the book on top of the stack
DSA Python
Hint

Use print(top_element) to display the top book.