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

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

đź‘‹ Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay