41
Stack in Python
Stack is a linear data structure that stores data in LIFO (Last In First Out) manners.
Web browser's back button is a stack application.
Web browser's back button is a stack application.
We perform two major operations in stack that are PUSH and POP.
The PUSH operation adds an element/ value in the stack, and the POP operation removes or deletes an element / value from the stack.
The PUSH operation adds an element/ value in the stack, and the POP operation removes or deletes an element / value from the stack.
There are various options to implement stack in Python.
Here, we discuss stack implementation using Python, and it’s modules.
Stack in Python can be implemented by following ways:
Here, we discuss stack implementation using Python, and it’s modules.
Stack in Python can be implemented by following ways:
Python list can be used as the stack.
List append() method used for adding elements in stack, which is similar to stack push operation.
List pop() method used for removing elements from stack, which is similar to stack pop() operation.
Python lists have performance issues.
The list push(), pop() operation becomes slow as it grows.
If the list grows and out of a block of memory then python allocates some memory.
This is the reason why Python lists become slow gradually.
The time complexity is O(n).
List append() method used for adding elements in stack, which is similar to stack push operation.
List pop() method used for removing elements from stack, which is similar to stack pop() operation.
Python lists have performance issues.
The list push(), pop() operation becomes slow as it grows.
If the list grows and out of a block of memory then python allocates some memory.
This is the reason why Python lists become slow gradually.
The time complexity is O(n).
Let's understand the following example
# Define empty stack
stack = []
# Add element to stack
stack.append(1)
stack.append(2)
stack.append(3)
stack.append(4)
stack.append(5)
print("Display stack after PUSH operation")
print(stack)
print("Remove element from stack")
print(stack.pop())
print(stack.pop())
print(stack.pop())
print(stack.pop())
print(stack.pop())
print("Display stack after POP operation")
print(stack)
Output:
Display stack after PUSH operation
[1, 2, 3, 4, 5]
Remove element from stack
5
4
3
2
1
Display stack after POP operation
[]
In above code, we defined empty list.
Then append some elements in stack, which is similar to stack PUSH() operation.
We also removed the elements using pop() method.
The pop() method returns the last element from the list.
Then append some elements in stack, which is similar to stack PUSH() operation.
We also removed the elements using pop() method.
The pop() method returns the last element from the list.
The Python collection module provides the deque class.
By using deque, we can create a stack.
The deque is pronounced as the deck which means double-ended queue.
The deque is better than Python list, because it's append and pop operation faster than the Python list.
The time complexity is O(1).
By using deque, we can create a stack.
The deque is pronounced as the deck which means double-ended queue.
The deque is better than Python list, because it's append and pop operation faster than the Python list.
The time complexity is O(1).
Let's understand the following example
# Define empty stack
from collections import deque
stack = deque()
# Add element to stack
stack.append(1)
stack.append(2)
stack.append(3)
stack.append(4)
stack.append(5)
print("Display stack after PUSH operation")
print(stack)
print("Remove element from stack")
print(stack.pop())
print(stack.pop())
print(stack.pop())
print(stack.pop())
print(stack.pop())
print("Display stack after POP operation")
print(stack)
Output:
Display stack after PUSH operation
[1, 2, 3, 4, 5]
Remove element from stack
5
4
3
2
1
Display stack after POP operation
[]
The Python queue module hase LifoQue, which is the same as stack.
It's have put() method to add element in stack and put() method to remove from stack.
It's have put() method to add element in stack and put() method to remove from stack.
Let's understand the following example
# Define empty stack
from queue import LifoQueue
stack = LifoQueue(maxsize=5)
print(f"Size of stack: {stack.qsize()}")
# Add element to stack
stack.put(1)
stack.put(2)
stack.put(3)
stack.put(4)
stack.put(5)
print(f"Stack is Full: {stack.full()}")
print(f"Size of Stack: {stack.qsize()}")
print("Remove element from stack")
print(stack.get())
print(stack.get())
print(stack.get())
print(stack.get())
print(stack.get())
print(f"Stack is Empty: {stack.empty()}")
Output:
Size of stack: 0
Stack is Full: True
Size of Stack: 5
Remove element from stack
5
4
3
2
1
Stack is Empty: True
Initially stack size is 0. Then we push 5 elements in stack using put() method.
Then, we check stack is full or not. Then, we check stack size.
After that, we remove element from stack using get() method.
Finally, we check does stack is empty or not.
Then, we check stack is full or not. Then, we check stack size.
After that, we remove element from stack using get() method.
Finally, we check does stack is empty or not.
We can use Python stack in multi-threaded program. Using list in multi-threading programming can dangerous because it's not thread safe.
The deque is a little complex because its append() and pop() method are atomic, which emans they will not interrupt by the other thread.
So, for build program of Python stack with treading, LifoQueue is better. It uses put() and get() to add and remove the stack element.
Although stack is a simple data structure to implement, it is very powerful.
The most common uses of a stack are:
The most common uses of a stack are:
2 + 4 / 5 * (7 - 9)
by converting the expression to prefix or postfix form.Expression Conversion - Converting one form of expressions to another is one of the important applications of stacks.
- Infix to prefix
- Infix to postfix
- Prefix to Infix
- Prefix to Postfix
- Postfix to Infix
- Postfix to Infix
Parenthesis Matching - Given an expression, you have to find if the parenthesis is either correctly matched or not. For example, consider the expression ( a + b ) * ( c + d
).
In the above expression, the opening and closing of the parenthesis are given properly and hence it is said to be a correctly matched parenthesis expression. Whereas, the expression, (a + b * [c + d )
is not a valid expression as the parenthesis are incorrectly given.
Used in many algorithms like Tower of Hanoi, tree traversals, stock span problem, histogram problem.
In Graph Algorithms like Topological Sorting and Strongly Connected Components
We have mentioned three methods of implement the stack in Python. The above methods have their own advantages or disadvantages.
We are using stack with the threading, you should use the LifoQueue but make sure about its performance for popping and pushing elements.
But if you are not using threading, use a deque.
But if you are not using threading, use a deque.
We can also use the list to implement the stack but the list can have potential memory reallocation issues. The list and deque are same in the interface, but the deque doesn't memory allocation issues.
41