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

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay