Trusted answers to developer questions

How to implement stack in Python

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2024 with this popular free course.

A stack is a last-in-first-out (LIFO) data structure. It has three primitive operations:

  • Push: Add an element to the stack
  • Pop: Remove an element from the stack
  • Peek: Get the topmost element of the stack
stack
stack

In Python, a stack is implemented using a list object.

  • To push an item in the stack, use the list function append list.append(item)
  • To pop an item in the stack, use the list function pop list.pop()
  • To get the top most item in the stack, write list[-1]

The following illustration explains the concept:

1 of 6

Example

The following code explains how to implement a stack in python:

class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return len(self.items) == 0
def push(self, item):
self.items.append(item)
def pop(self):
if not self.is_empty():
return self.items.pop()
else:
print("Stack is empty")
def peek(self):
if not self.is_empty():
return self.items[-1]
else:
print("Stack is empty")
def size(self):
return len(self.items)
# Example usage:
if __name__ == "__main__":
stack = Stack()
stack.push("a")
stack.push("b")
stack.push("c")
print("Stack:", stack.items)
print("Number of items in stack", stack.size())
print("The top value in the stack is:", stack.peek())
value_popped = stack.pop()
print("Value removed from Stack:", value_popped)
print("Remaining elements in Stack are:", stack.items)

Explanation

The above example uses a list to store the elements of the stack.

  • is_empty(): Checks if the stack is empty.

  • push(item): Adds an item to the top of the stack.

  • pop(): Removes and returns the item at the top of the stack.

  • peek(): Returns the item at the top of the stack without its removal

  • size(): Returns the number of elements present in the stack.

Test your knowledge!

Write a Python program to reverse a string using a stack data structure. The program should take this string Educative and utilize a stack to reverse the order of characters in the string. Please use the widget provided below to write the program and execute the program by clicking on the "Run" button.

If you feel stuck at any point click the "Solution" button to see the solution of the problem.

class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return len(self.items) == 0
def push(self, item):
self.items.append(item)
def pop(self):
if not self.is_empty():
return self.items.pop()
else:
print("Stack is empty")
def size(self):
return len(self.items)
def reverse_string(input_string):
"""Function to reverse a string using a stack."""
stack = Stack()
# Push each character onto the stack
# WRITE YOUR CODE HERE
# Pop each character from the stack to get reversed order
while not stack.is_empty():
#WRITE YOUR CODE HERE
return reversed_string
def main():
"""Main function to accept user input and reverse the string."""
input_string = "Educative"
#WRITE YOUR CODE HERE
print("Reversed string:", reversed_string)
if __name__ == "__main__":
main()

RELATED TAGS

stack
python
push
pop
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?