Python Stack (Implementation Tutorial with Examples)

Python Stack

This is a tutorial to implement a Stack in Python. Learn to create a stack and to 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 of which was lastly inserted. The insertion, as well as the deletion, happens at the same end. That’s why its called as 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() – To insert a new item at the top of the stack.
  • pop() – To remove the last item present at the top of the stack.
  • empty() – To check if the stack is empty or not.
  • top() – To get the item present at the top of the stack.
  • size() – To check the number of items present in the stack.

Now, that you know what is a stack and what are the different operations associated with it, let 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 of the people are familiar with it. Let’s first implement a stack using a list in the following example and then figure out if it 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’ve used the Python List insert() method to insert 6 different items. Now the stack contains the inserted 6 items as the printed in the second line of the console output. Then we’ve popped out top 3 items one by one using 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 as in the same order they were popped out. Finally, the Updated Stack has 3 items left. We have used the 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 if-else statement in association with the condition formed using 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 wit 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, maximum number of methods are 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.

And do not forget to subscribe to WTMatter!

Subscribe To WTMatter!

Receive updates of our latest articles via email. Enter your email address below to get started.

Leave a Reply

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