
Stack in Python – A Complete Guide
Stack in Python
Introduction
In this tutorial, we will explore the fundamental concept of stacks in Python. We will understand how stacks work, their real-world applications, and different ways to implement them in Python.
What is a Stack?
According to the LIFO (Last In, First Out) principle, a stack is a linear data structure. This means that the last element added to the stack will be the first one to be removed, just like a stack of plates in a kitchen.
Complete Python Course with Advance topics:-Click here
Real-World Examples:
- Undo feature in text editors – The last action performed is undone first.
- Back button in web browsers – The last visited page is accessed first.
- Function call stack in programming – Functions execute in a LIFO order.
Stack Operations:
- PUSH – Adds an element to the top of the stack.
- POP: Takes the top element out of the stack and returns it.
- The top element is returned by PEEK (TOP) without being removed.
- IS EMPTY: Verifies that there is nothing in the stack.
- SIZE: Indicates how many items are in the stack.
Methods of Stack in Python
Python provides the following built-in methods to implement a stack:
Method | Description | Time Complexity |
---|---|---|
empty() |
Returns True if the stack is empty, otherwise False . |
O(1) |
size() |
Returns the number of elements in the stack. | O(1) |
top() |
Returns the topmost element without removing it. | O(1) |
push(g) |
Adds element g to the stack. |
O(1) |
pop() |
Removes and returns the top element. | O(1) |
Implementing Stack in Python
There are three common ways to implement a stack in Python:
- Using a list
- Using
collections.deque
- Using
queue.LifoQueue
1. Implementation Using List
Python’s built-in list can be used to implement a stack using append()
for push operations and pop()
for pop operations.
# Stack implementation using list
my_stack = []
# Push elements onto the stack
my_stack.append('A')
my_stack.append('B')
my_stack.append('C')
print("Stack after pushing elements:", my_stack)
# Pop elements from the stack
print("Popped element:", my_stack.pop())
print("Popped element:", my_stack.pop())
print("Popped element:", my_stack.pop())
print("Stack after popping elements:", my_stack)
Output:
Stack after pushing elements: ['A', 'B', 'C']
Popped element: C
Popped element: B
Popped element: A
Stack after popping elements: []
Drawbacks of Using Lists:
- Lists are not optimized for stack operations.
pop()
operation can be slow when the list grows due to memory reallocation.
2. Implementation Using collections.deque
The deque
(double-ended queue) from the collections
module provides a more efficient way to implement a stack.
from collections import deque
# Stack implementation using deque
my_stack = deque()
# Push elements onto the stack
my_stack.append('X')
my_stack.append('Y')
my_stack.append('Z')
print("Stack after pushing elements:", my_stack)
# Pop elements from the stack
print("Popped element:", my_stack.pop())
print("Popped element:", my_stack.pop())
print("Popped element:", my_stack.pop())
print("Stack after popping elements:", my_stack)
Output:
Stack after pushing elements: deque(['X', 'Y', 'Z'])
Popped element: Z
Popped element: Y
Popped element: X
Stack after popping elements: deque([])
Advantages of deque
over List:
- Faster append and pop operations.
- No memory reallocation issues.
3. Implementation Using queue.LifoQueue
Python’s queue
module provides a LifoQueue, which is a thread-safe stack implementation.
from queue import LifoQueue
# Stack implementation using LifoQueue
my_stack = LifoQueue(maxsize=5)
# Push elements onto the stack
my_stack.put('1')
my_stack.put('2')
my_stack.put('3')
print("Stack is full:", my_stack.full())
print("Stack size:", my_stack.qsize())
# Pop elements from the stack
print("Popped element:", my_stack.get())
print("Popped element:", my_stack.get())
print("Popped element:", my_stack.get())
print("Stack is empty:", my_stack.empty())
Output:
Stack is full: False
Stack size: 3
Popped element: 3
Popped element: 2
Popped element: 1
Stack is empty: True
Advantages of LifoQueue
:
- Thread-safe (suitable for multithreading applications).
- Provides additional methods like
maxsize()
,empty()
, andfull()
.
Choosing the Right Stack Implementation
Implementation | Use Case |
---|---|
List | Suitable for small programs, but may have performance issues with large data. |
Deque | Best choice for non-threaded applications due to fast push/pop operations. |
LifoQueue | Recommended for multi-threaded applications. |
Download New Real Time Projects :-Click here
Complete Advance AI topics:- CLICK HERE
Conclusion
In this guide, we covered the stack data structure, its operations, and three different ways to implement it in Python. Depending on your use case, you can choose between lists, deque, or LifoQueue for an optimized and efficient stack implementation.
Stay connected with UpdateGadh for more in-depth programming tutorials!
queue in python
stack in python w3schools
stack program in python class 12
stack in c
Stack in Python – A Complete Guide
stack data structure in python
how to get top element of stack in python
stack implementation using list in python
stack.pop python
list in python
Stack in Python – A Complete Guide
linked list in python
stack in python geeksforgeeks
Post Comment