Stack with Python

The stack is a type of restricted container that stores a linear collection. Stacks are very common in computer science and are used in many types of problems related to data structures and algorithms. In this article, I’ll walk you through how to build a stack with Python.

What are Stacks?

Consider a stack of trays in a dining room. When one tray is removed from the top, the others move up. If any trays are placed on the stack, the others are pushed down. A stack is used to store data so that the last item inserted is the first item deleted. It is used to implement a last-in, first-out (LIFO) protocol.

The stack is a linear data structure in which new items are added, or existing items are removed from the same end, commonly known as the top of the stack. The opposite end is known as the base.

Let’s have a look at some functions of Stacks that can be made with Python or any other programming language:

  1. Stack(): This creates a new empty stack.
  2. isEmpty(): It returns a Boolean value indicating whether the stack is empty.
  3. length(): It returns the number of items in the stack.
  4. pop(): It removes and returns the top item from the stack if it is not empty. Items cannot be removed from an empty stack. The next item becomes the new top item.

Stack with Python: Problem Statement

I’ll apply a stack with Python to the problem of inverting a list of integer values. The values will be retrieved from the user until a negative value is entered, which marks the end of the collection. The values will then be printed in the reverse order of how they were entered. 

We can also use a simple list for this problem, but a stack is an ideal choice for this problem statement because values can be pushed onto the stack as they are entered, then skipped one by one to print them in reverse order.

Implementing Stack with Python

Now let’s see how to implement the above stack problem with Python. I will first create a Python class for Stack as it is not included in the objects and data structures of Python. So let’s create a class for Stack with Python and implement the above problem statement:

Enter an int value : 6
Enter an int value : 8
Enter an int value : 5
Enter an int value : 8
Enter an int value : 9
Enter an int value : -1

When the outer while loop ends after extracting the negative value, note that the last value entered is at the top and the first at the bottom. I hope you liked this article on how to implement a Stack with Python. Feel free to ask your valuable questions in the comments section below.

Default image
Aman Kharwal

I am a programmer from India, and I am here to guide you with Data Science, Machine Learning, Python, and C++ for free. I hope you will learn a lot in your journey towards Coding, Machine Learning and Artificial Intelligence with me.

Leave a Reply