Stack Data Structure and Implementation in Python


In computer science, a data structure is a way to store and organize data, and it helps to use the data efficiently. In this article, let’s learn what stack data structure is and how to implement it using Python.

Stack is a data structure that stores items in a Last In First Out (LIFO) manner, which means that the last element inserted inside the stack is removed first. In stack, insertion and deletion of elements are allowed only at one end. The other end is closed.

The process of inserting items into the stack is called push and the process of removing items from the stack is called pop. To understand the working of the stack data structure, have a look at the following diagrams.

Here, the stack is represented by ash-colored lines. The yellow, green, and blue circles are items that we will use to do push and pop operations.

Let’s say we have an empty stack. We are pushing items into the stack one by one.

stack push operation

As you can see, we have inserted the yellow item first, followed by the blue item and then the green item. We can use a pointer called top to keep track of the top element in the stack.

Now, let’s see how we can pop these items from the stack. Since it is a LIFO (Last In First Out) data structure, the item that was pushed last will be popped first. If you want to pop the item at the bottom, you must first remove all the items on top.

stack pop operation

Stack Implementation using Python

Let’s try to implement this data structure in the Python programming language. There are various ways to implement stack data structure in Python. We will do it in the easiest way, which is by using a list.

The list is an in-built data structure in Python, and it can be used as a stack. We can use the append() method to push elements to the top of the stack. We also have the pop() method which removes the items in LIFO order. 

Given below is the Python code that implements the stack data structure.

stack = []

stack.append('Yellow')
stack.append('Blue')
stack.append('Green')

print('Stack after elements are pushed:')
print(stack)

print('\nPopping items from the stack:')
print(stack.pop())
print(stack.pop())
print(stack.pop())

print('\nStack after elements are popped:')
print(stack)

Output:

stack implementation in Python - output

If you haven’t understood the working of stack yet, check out this online tool, where you can visualize the concepts and play around with stack.

Ashwin Joy

I'm the face behind Pythonista Planet. I learned my first programming language back in 2015. Ever since then, I've been learning programming and immersing myself in technology. On this site, I share everything that I've learned about computer programming.

Leave a Reply

Your email address will not be published. Required fields are marked *

Recent Posts