DEV Community

Cover image for Data Structures in Python -Stack
LetsUpdateSkills
LetsUpdateSkills

Posted on

Data Structures in Python -Stack

In Python, like any other programming language, the stack is a linear data structure that operates on the LIFO principle. This means that the element added last will be removed from the stack first.

Understand Stack with a Scenario:
Think of it like a stack of plates, where the only actions you can take are to add or remove the top plate. Common operations include "push," which adds an item, "pop," which removes the top item, and "peek," which allows you to see the top item without removing it.

Common Operation on Stack

There are the following common operations on the stack:

  • Push: Adds an element to the top of the stack.
  • Pop: Removes and returns the top element from the stack.
  • Peek: Returns the top element without removing it.
  • is_empty: Checks if the stack is empty.
  • size: Returns the number of elements in the stack.

How to Create a Stack
To create a stack in Python, we can use various approaches, depending on our needs. Here's how you can create and work with a stack using different methods:

Using List
Lists in Python can act as a stack because they support append() for adding elements and pop() for removing the last element.

# Stack implementation using a list
stack = []

# Push elements onto the stack
stack.append(1)
stack.append(2)
stack.append(3)

print("Stack after pushing elements:", stack)

# Pop an element from the stack
popped_element = stack.pop()
print("Popped element:", popped_element)
print("Stack after popping:", stack)

# Peek the top element
if stack:
    print("Top element:", stack[-1])
else:
    print("Stack is empty.")
Enter fullscreen mode Exit fullscreen mode

https://www.letsupdateskills.com/tutorials/learn-python-intermediate/data-structures-stack

Top comments (0)