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:
- Stack(): This creates a new empty stack.
- isEmpty(): It returns a Boolean value indicating whether the stack is empty.
- length(): It returns the number of items in the stack.
- 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
9
8
5
8
6
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.