This tutorial explains what is Python Stack and various ways to implement Stack in Python. Each method is explained using practical examples:
In Python, a Stack is a data structure that works on the “ LIFO ” principle. It stores the elements in the Last-In/First-Out criteria. The element which gets stored at the last will pop out first.
It works opposite to the Queue data structure in Python which works on the ” FIFO “ principle. It is very simple and easy to understand the Stack data structure if one should be familiar with the UNDO feature in the editors.
=> Check ALL Python Tutorials Here
Table of Contents:
Python Stack Data Structure
The best example to understand the Stack data structure is “a box of Pringles Chips”. The last Pringle chip added to the box will come out first.
It admits the two operations push and pop from one end, which is called a top. We can insert or delete the info elements from the top.
Basic Operations of Stack
The basic operations of Stack are mentioned below:
- Push: It is used to insert the elements into the Stack. If the Stack is full, then the Overflow condition will occur.
- Pop: It is used to delete the element from the Stack. Once the Stack is empty, the Underflow condition will occur.
- Peek or Top: It will return the top element from the Stack.
- isEmpty: If the Stack is empty, then it will return TRUE as an output otherwise it will return FALSE.
Applications of Stack
Stack is known as the backbone of the Data Structure in Python. Almost all the algorithms are implemented using the Stack.
- Stack works on the LIFO principle i.e. they are used to reverse the string.
- Stack is used in Expression Evaluation and Expression Conversion.
- It is also used in web browsers for the forward and the backward features.
- It is used for syntax parsing.
- It is used for Backtracking in the searching algorithms.
Implementation of Stack in Python
Python provides various choices for implementing the Python Stack. We can use it with Python lists, Python tuples, or by using the Python third-party packages. Generally, there are a few basic techniques to implement the Stack which will attain the developers’ needs.
Given below are few implementations:
- List
- Collections.deque
- queue.LifoQueue
Python Stack by Using List
In Python, List is a built-in data structure that can be used as a Stack. We can use lists frequently to write the Python code. They are implemented as internal dynamic arrays i.e. whenever the element is inserted or deleted, the storage area will be resized automatically.
We can use the “ .append() “ function to insert the elements and the “ .pop() “ function to delete the element from Stack in Python.
Example – Adding the elements to the Stack
In this example, we are adding the elements to the stack using the “.append()” function.
``` demo_stack = [] # Creating a empty list demo_stack.append('Software') # Appending the elements to the list demo_stack.append('Testing') demo_stack.append('Help') print( " The demo stack is: ", demo_stack) ```
Example – Deleting the elements from the stack
In this example, we are deleting the elements from the stack using the “.pop()” function.
``` demo_stack = [] demo_stack.append('Software') demo_stack.append('Testing') demo_stack.append('Help') print( " The demo stack is: ", demo_stack ) demo_stack.pop() # Deleting the elements from the stack demo_stack.pop() print("The demo stack after popping: ", demo_stack) ```
Getting an Error: pop from empty list
``` demo_stack = [] demo_stack.append('Software') demo_stack.append('Testing') demo_stack.append('Help') print("The demo stack is: ", demo_stack) demo_stack.pop() demo_stack.pop() demo_stack.pop() demo_stack.pop() print( " The demo stack after popping: ", demo_stack ) ```
In the output, you will see the error occurs because we have three elements in the Stack and we are trying to pop out four elements. This error shows that the given Stack is empty now.
The lists can work efficiently when implemented as Stacks but have some disadvantages. There can be a situation when the size of the Stack becomes bigger than the present block of the memory it holds. By using the lists in Python, we can access the random elements fast but in that case, speed issues can occur.
Python Stack by Using Array
Stacks that are implemented using the Python arrays are the same as they are implemented using the Python lists. If one should imagine that the Python lists are the same as arrays in Python, then the below-given algorithm will help you to understand its working.
Algorithm:
- Initialize the Python list and an integer named “ MaximumSize ”.
- Set the Top_of_the_stack equal to zero.
- Stack Push operation:
- Check whether the MaximumSize is larger than the Top_of_the_stack or not.
- If larger, then append the element to the Stack and enlarge its size by 1.
- If smaller, then print the full message of Stack.
- Check whether the MaximumSize is larger than the Top_of_the_stack or not.
- Stack Pop operation:
- Check whether the Top_of_the_stack is larger than zero or not.
- If larger then, pop the last data element from the list and reduce its size by 1.
- If smaller then, print the empty Stack message.
- Check whether the Top_of_the_stack is larger than zero or not.
``` class Demo_Stack: def __init__(self): self.demo_stack = list() self.maximumSize = 5 self.top_of_the_stack = 0 # Insert the element to the Stack def push(self,element): if self.top_of_stack>=self.maximumSize: return ( " The given stack is full! " ) self.demo_stack.append(element) self.top_of_the_stack += 1 return True # Delete the element from the stack def pop(self): if self.top_of_the_stack<=0: return ( " The given stack is empty! " ) item = self.demo_stack.pop() self.top_of_the_stack -= 1 return item def size(self): return self.top_of_the_stack demo_data = Demo_Stack() print(demo_data.push(10)) # prints True print(demo_data.push(20)) # prints True print(demo_data.push(30)) # prints True print(demo_data.push(40)) # prints True print(demo_data.push(50)) # prints True print(demo_data.push(60)) # prints True print(demo_data.push(70)) # prints True print(demo_data.push(80)) # prints True print(demo_data.push(90)) # prints Stack Full! print(demo_data.size()) # prints 8 print(demo_data.pop()) # prints 80 print(demo_data.pop()) # prints 70 print(demo_data.pop()) # prints 60 print(demo_data.pop()) # prints 50 print(demo_data.pop()) # prints 40 print(demo_data.pop()) # prints 30 print(demo_data.pop()) # prints 20 print(demo_data.pop()) # prints 10 print(demo_data.pop()) # prints Stack is Empty! ```
Python Stack by Using collections.deque
Python supports the module named collections. This module contains the “ deque “ class which supports the adding and deleting of the elements from both the ends and acts as a double-ended queue. The deque methods will work similar to the Python lists.
Let us understand this by taking an example.
Example – Adding elements using the deque module.
In this example, we are using the deque module to add the elements to the stack. For this the “.append()” function is used.
``` from collections import deque # importing the deque module demo_stack = deque() demo_stack.append('A') # Adding the elements to the stack demo_stack.append('B') demo_stack.append('C') print ("The demo stack using deque: ",demo_stack) ```
Example – Deleting elements using the deque module
In this example, we are using the deque module to delete the elements from the stack. For this the “.pop()” function is used.
``` from collections import deque demo_stack = deque() demo_stack.append('A') demo_stack.append('B') demo_stack.append('C') print ("The demo stack using deque: ",demo_stack) demo_stack.pop() demo_stack.pop() demo_stack.pop() print("The demo stack after deleting the elements: ", demo_stack) ```
Getting an Error: pop from an empty deque
``` from collections import deque demo_stack = deque() demo_stack.append('A') demo_stack.append('B') demo_stack.append('C') print ("The demo stack using deque: ",demo_stack) demo_stack.pop() demo_stack.pop() demo_stack.pop() print( " The demo stack after deleting the elements: ", demo_stack ) demo_stack.pop() # We will get an error because here the stack is already empty. ```
The error occurs just because we are trying to pop the element from the empty stack.
Python Stack Using queue.LifoQueue
The Standard library of Python contains various classes, and one of them is the “ queue.LifoQueue “ class which is again used to implement the Stack in Python. It carries various concurrent producers and consumers.
In Python, the concept used for executing various independent tasks & function calls parallelly is known as threading. This Python queue module can be helpful when the developer is working with multiple threads and performing parallel computing.
In this method, we will use “ .put() ” and “ .get() “ to perform insertion and deletion of the elements from the Stack.
In this example, we are inserting the elements to the stack and deleting the elements from the stack using the functions mentioned above.
``` from queue import LifoQueue # Importing the class demo_stack = LifoQueue() demo_stack.put('A') # Inserting the elements demo_stack.put('B') demo_stack.put('C') print(demo_stack) demo_stack.get() # Deleting the elements demo_stack.get() demo_stack.get() print(demo_stack) ```
Frequently Asked Questions
Q #1) Is there a Stack in Python?
Answer: Yes, Python has a built-in data structure named Stack. It supports push and pop operations that are used to add the elements to the Stack and delete the elements from the Stack.
Python Lists are executed as dynamic arrays i.e. they point to resize the space storage for the elements that are getting stored in the Stack or deleted from the Stack.
Q #2) What is __ init __ Python?
Answer: In Python “ __init__ ” is a booked method in Python classes. It is called the constructor in object-oriented Python programs. This method allows the class to initialize attributes of a class and call when the object is created from the class.
Q #3) Is Stack a list?
Answer: Python Stack is a list-like data structure that works on the LIFO criteria list, which means Last-In-First-Out. The elements that are inserted at the last will be popped out first. Array-based and the linked Stack can be easy to implement.
Q #4) Give an example of Stack?
Answer: The best examples to understand the Stack data structure is a pile of books, Stack of dinner plates, Pringle chips, etc.
Q #5) Why is Stack called LIFO?
Answer: LIFO is called “ Last-In-First-Out “. The last element inserted in the Stack will be the first element that comes first out from the Stack. If the user will pop all the Stack elements then, at one time the elements will appear in the reverse order to the order they were inserted in the Stack.
Conclusion
In the above tutorial, we discussed the Stack data structure in Python.
Stack data structures allow the user to store and get back the data in a consecutive way.
Having a deep knowledge of Stack data structures will help the software developers to solve the problems related to data storage in a well-organized manner.
=> Visit Here To Learn Python From Scratch