Python Stack and its Implementation

This is a tutorial to implement a Stack in Python. Learn to create a stack and perform different operations on it like push, pop, empty, top, size, etc.

Stack

A Stack is basically a linear data structure with LIFO (Last In, First Out) properly. In other words, a stack is such a data type in which the new item can only be inserted at the top and the only item that can be removed at a time is the item present at the top of the stack which was lastly inserted. The insertion, as well as the deletion, happens at the same end. That’s why it’s called a Last In, First Out (LIFO) data structure.

The following image visually illustrates a Stack Data Structure.

Stack Data Structure

There are some operations that can be performed on a Stack Data Structure that are briefly described below.

push()
pop()
empty()
top()
size()

Now, that you know what is a stack and what the different operations associated with it are, let’s figure out how to implement a stack in Python.

Python Stack Implementation

Stacks can be implemented in Python using a lot of different ways and using already available data structures. In this article, I’ve shared three different ways to implement a stack in Python. These ways are listed below.

  • Using Python List
  • Using Python Collections Module
  • Using Python Queue Module

Implementation using List

Python List is a built-in data type and most people are familiar with it. Let’s first implement a stack using a list in the following example and then figure out if it is an efficient way of stack implementation or not.

Code.

#Stack Implementation Program
#Using Python List
stack = []

print("Empty Stack:", stack)

#Push Operation
#Using append() Method
stack.append("Gurmeet")
stack.append("Daman")
stack.append("Deepinder")
stack.append("Jaskaran")
stack.append("Sukhman")
stack.append("Prabhleen")

print("Filled Stack: ", stack)

#Pop Operation
#Using pop() method
print("Popped Item:", stack.pop())
print("Popped Item:", stack.pop())
print("Popped Item:", stack.pop())

print("Updated Stack:", stack)

#Item at the top of Stack
print("Item at Stack Top:", stack[-1])

#Stack Size
#using len() method
print("Current Stack Size:", len(stack))

#Check if stack is empty or not
if not stack:
    print("Stack is Empty!")
else:
    print("Stack is Not Empty!")

Output.

Empty Stack: []
Filled Stack:  ['Gurmeet', 'Daman', 'Deepinder', 'Jaskaran', 'Sukhman', 'Prabhleen']
Popped Item: Prabhleen
Popped Item: Sukhman
Popped Item: Jaskaran
Updated Stack: ['Gurmeet', 'Daman', 'Deepinder']
Item at Stack Top: Deepinder
Current Stack Size: 3
Stack is Not Empty!

Here we’ve created a Python List and referred it to the variable named stack. As there are no items currently in this list, so the stack is empty and hence the print statement displays an empty stack in the first line of the code output. Then we used the pop() method.

As the pop() method also returns the popped item, therefore, we’ve printed the popped items to the console as well and they are printed in three different lines in the same order they were popped out. Finally, the Updated Stack has 3 items left. We have used indexing to check the last item of the list or the topmost item of the stack. Using the built-in len() function, we’ve also verified the size of the stack. In the end, we’ve used the not operator.

Although, Python List is an easy way to implement a Stack Data Structure yet it is not the best and the most efficient way.

Implementation using collections Module

We can use the deque class of the Collections module to implement a stack. This method is faster for the push and pop operations than the list method.

Code.

#Stack Implementation Program
#Using Collections Module's deque Class
from collections import deque

stack = deque()

print("Empty Stack:", stack)

#Push Operation
#Using append() Method
stack.append("Gurmeet")
stack.append("Daman")
stack.append("Deepinder")
stack.append("Jaskaran")
stack.append("Sukhman")
stack.append("Prabhleen")

print("Filled Stack: ", stack)

#Pop Operation
#Using pop() method
print("Popped Item:", stack.pop())
print("Popped Item:", stack.pop())
print("Popped Item:", stack.pop())

print("Updated Stack:", stack)

#Item at the top of Stack
print("Item at Stack Top:", stack[-1])

#Stack Size
#using len() method
print("Current Stack Size:", len(stack))

#Check if stack is empty or not
if not stack:
    print("Stack is Empty!")
else:
    print("Stack is Not Empty!")

Output.

Empty Stack: deque([])
Filled Stack:  deque(['Gurmeet', 'Daman', 'Deepinder', 'Jaskaran', 'Sukhman', 'Prabhleen'])
Popped Item: Prabhleen
Popped Item: Sukhman
Popped Item: Jaskaran
Updated Stack: deque(['Gurmeet', 'Daman', 'Deepinder'])
Item at Stack Top: Deepinder
Current Stack Size: 3
Stack is Not Empty!

The program works exactly in the same way as it worked in the previous example of stack implementation using the list. The only difference is that here we’ve used the deque() class of the collections module to create the stack instead of a list. Even the method names are also exactly the same.

Implementation Using queue Module

You can use the queue module to implement different types of queue-type data structure implementations using Python. We’ll use it for stack implementation because it is also a queue-type data structure with LIFO order. So, to implement a LIFO queue with this module, we’ve to use its LifoQueue class as illustrated in the following program.

Code.

#Stack Implementation Program
#Using queue Module's LifoQueue Class
from queue import LifoQueue

stack = LifoQueue(maxsize = 6)

print("Empty Stack:", stack.queue)

#Push Operation
#Using put() Method
stack.put("Gurmeet")
stack.put("Daman")
stack.put("Deepinder")
stack.put("Jaskaran")
stack.put("Sukhman")
stack.put("Prabhleen")

print("Filled Stack: ", stack.queue)

#To Check if Stack if FULL
#using full() method
print("Is the Stack Full?", stack.full())

#Pop Operation
#Using get() method
print("Popped Item:", stack.get())
print("Popped Item:", stack.get())
print("Popped Item:", stack.get())

print("Updated Stack:", stack.queue)

#Item at the top of Stack
print("Item at Stack Top:", stack.queue[-1])

#Stack Size
#using qsize() method
print("Current Stack Size:", stack.qsize())

#Check if stack is empty or not
#Using empty() method
if stack.empty():
    print("Stack is Empty!")
else:
    print("Stack is Not Empty!")

Output.

Empty Stack: []
Filled Stack:  ['Gurmeet', 'Daman', 'Deepinder', 'Jaskaran', 'Sukhman', 'Prabhleen']
Is the Stack Full? True
Popped Item: Prabhleen
Popped Item: Sukhman
Popped Item: Jaskaran
Updated Stack: ['Gurmeet', 'Daman', 'Deepinder']
Item at Stack Top: Deepinder
Current Stack Size: 3
Stack is Not Empty!

To create a Stack you have to call the LifeQueue class using the constructor method and have to provide the size of the list as the max size keyword, integer-type argument. Then, you can insert items into this stack one by one using the put() method. To print the items of the queue at any time, use the queue property. Example, stack.queue

To check if the stack is full or empty, you can use the full() and empty() methods respectively. The qsize() method returns the number of times present in the current stack. Instead of the pop() method, here we have the get() method that removes the last or the topmost item of the stack and also returns it.

Among all of the above three methods, the maximum number of methods is provided in the third method, while the first method is the simplest and the easiest one.

I hope you found this guide useful. If so, do share it with others who are willing to learn Python. If you have any questions related to this article, feel free to ask us in the comments section.

Leave a Reply

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