DEV Community

Cover image for Using Python to understand Stacks

Using Python to understand Stacks

bengineer52 profile image bengineer Updated on ・2 min read

What is it?

In computer science, a stack is an abstract data type that serves as a collection of elements, with two main principal operations:

  • push, which adds an element to the collection, and
  • pop, which removes the most recently added element that was not yet removed.

The order in which elements come off a stack gives rise to its alternative name, LIFO (last in, first out). Additionally, a peek operation may give access to the top without modifying the stack. The name "stack" for this type of structure comes from the analogy to a set of physical items stacked on top of each other. This structure makes it easy to take an item off the top of the stack, while getting to an item deeper in the stack may require taking off multiple other items first.

Implementation in Python 3

class Stack:
    def __init__(self):
        self._stack = []

    def push(self, item):

    def pop(self):
        return self._stack.pop()

    def peek(self):
        return self._stack[-1]

    def is_empty(self):
        return len(self._stack) == 0

Note: This post is educational. If you want to use Stacks on your projects, it's recommended to search for a more optimized implementation.


>>> stack = Stack()


Push (Adds an item to the stack)

>>> stack.push(1)
>>> stack.push(2)
>>> stack.push(3)

Pop (Remove top item from the stack and returns it)

>>> stack.pop()

Peek (Get the top item, without removing it from the stack)

>>> stack.peek()

Is Empty? (Returns True if the stack is empty, and False if it is not)

>>> stack.is_empty()

Would like to see more posts like this? Please let me know in the comments =)


Editor guide