For working professionals
For fresh graduates
More
13. Print In Python
15. Python for Loop
19. Break in Python
23. Float in Python
25. List in Python
27. Tuples in Python
29. Set in Python
53. Python Modules
57. Python Packages
59. Class in Python
61. Object in Python
73. JSON Python
79. Python Threading
84. Map in Python
85. Filter in Python
86. Eval in Python
96. Sort in Python
101. Datetime Python
103. 2D Array in Python
104. Abs in Python
105. Advantages of Python
107. Append in Python
110. Assert in Python
113. Bool in Python
115. chr in Python
118. Count in python
119. Counter in Python
121. Datetime in Python
122. Extend in Python
123. F-string in Python
125. Format in Python
131. Index in Python
132. Interface in Python
134. Isalpha in Python
136. Iterator in Python
137. Join in Python
140. Literals in Python
141. Matplotlib
144. Modulus in Python
147. OpenCV Python
149. ord in Python
150. Palindrome in Python
151. Pass in Python
156. Python Arrays
158. Python Frameworks
160. Python IDE
164. Python PIP
165. Python Seaborn
166. Python Slicing
168. Queue in Python
169. Replace in Python
173. Stack in Python
174. scikit-learn
175. Selenium with Python
176. Self in Python
177. Sleep in Python
179. Split in Python
184. Strip in Python
185. Subprocess in Python
186. Substring in Python
195. What is Pygame
197. XOR in Python
198. Yield in Python
199. Zip in Python
A stack in Python is a collection of elements that follows the LIFO (Last In, First Out) principle, meaning the last element added is the first one to be removed. This data structure is fundamental for various algorithms and applications, such as managing function calls and undo operations.
However, understanding how to implement a stack and its operations can be tricky for beginners. Whether you're managing data, solving problems like balancing parentheses, or simply learning the core concepts of Python, you need to grasp stack functionality well.
In this guide, you’ll see how a stack program in Python works and how you can implement it effectively.
By the end of this tutorial, you’ll have a clear understanding of stack in Python with example. Read on to learn more!
“Enhance your Python skills further with our Data Science and Machine Learning courses from top universities — take the next step in your learning journey!”
A stack in Python is typically implemented using a list, and there are several core methods used to manipulate the stack: push, pop, peek, and isEmpty.
Let's go through them one by one, with examples to help you understand their practical application.
The push operation adds an element to the top of the stack. In Python, this is done using the append() method, which appends the element to the list.
stack = [] # Initial empty stack
stack.append(10) # Push 10 onto the stack
stack.append(20) # Push 20 onto the stack
# Output the stack
print("Stack after pushing:", stack)
Output:
Stack after pushing: [10, 20]
Explanation:
The pop operation removes the element at the top of the stack. This is done using the pop() method. If the stack is empty, attempting to pop will raise an error.
stack.pop() # Removes 20, the topmost element
# Output the stack after pop
print("Stack after popping:", stack)
Output:
Stack after popping: [10]
Explanation:
The peek operation allows you to view the top element without removing it. Python does not have a built-in method for this, but you can access the top element directly using index -1.
top_element = stack[-1] # Get the top element without removing it
# Output the top element
print("Top element:", top_element)
Output:
Top element: 10
Explanation:
The isEmpty method checks if the stack has any elements. Python can do this by simply checking the list’s length.
is_empty = len(stack) == 0 # Check if the stack is empty
# Output whether the stack is empty
print("Is the stack empty?", is_empty)
Output:
Is the stack empty? False
Explanation:
“Start your coding journey with our complimentary Python courses designed just for you — dive into Python programming fundamentals, explore key Python libraries, and engage with practical case studies!”
The list data structure in Python comes with built-in methods like append() for adding items (push operation) and pop() for removing items (pop operation).
Here’s an implementation of a simple stack using Python's list:
class Stack:
def __init__(self):
self.stack = [] # Create an empty list to represent the stack
# Push operation: Adds an element to the stack
def push(self, value):
self.stack.append(value)
# Pop operation: Removes the top element from the stack
def pop(self):
if not self.is_empty():
return self.stack.pop()
else:
return "Stack is empty!"
# Peek operation: Returns the top element without removing it
def peek(self):
if not self.is_empty():
return self.stack[-1]
else:
return "Stack is empty!"
# Check if the stack is empty
def is_empty(self):
return len(self.stack) == 0
# Get the current size of the stack
def size(self):
return len(self.stack)
Explanation of Code:
Example Usage
# Creating a stack object
my_stack = Stack()
# Pushing elements onto the stack
my_stack.push(10) # Stack is now [10]
my_stack.push(20) # Stack is now [10, 20]
my_stack.push(30) # Stack is now [10, 20, 30]
# Output the current stack
print("Current Stack:", my_stack.stack)
# Peek the top element
print("Top Element:", my_stack.peek())
# Pop an element from the stack
print("Popped Element:", my_stack.pop())
print("Stack After Pop:", my_stack.stack) # Stack is now [10, 20]
# Check if the stack is empty
print("Is Stack Empty?", my_stack.is_empty())
# Get the size of the stack
print("Stack Size:", my_stack.size())
Output:
Current Stack: [10, 20, 30]Top Element: 30Popped Element: 30Stack After Pop: [10, 20]Is Stack Empty? FalseStack Size: 2
Explanation:
This is a simple stack in Python with example using a list. By implementing these stack operations, you can easily handle data in a LIFO manner.
Also Read: Data Structures in Python
While using a list for stack operations in Python works, there’s a more efficient way to implement a stack using collections.deque.
The deque (double-ended queue) is part of Python’s collections module and is optimized for fast append and pop operations from both ends. This makes it ideal for implementing a stack since the push and pop operations will have constant time complexity, i.e., O(1), unlike a list, which has O(n) for pop from the front.
Here’s the implementation of a stack using deque:
from collections import deque # Import deque from the collections module
class Stack:
def __init__(self):
self.stack = deque() # Create an empty deque to represent the stack
# Push operation: Adds an element to the stack
def push(self, value):
self.stack.append(value)
# Pop operation: Removes the top element from the stack
def pop(self):
if not self.is_empty():
return self.stack.pop()
else:
return "Stack is empty!"
# Peek operation: Returns the top element without removing it
def peek(self):
if not self.is_empty():
return self.stack[-1]
else:
return "Stack is empty!"
# Check if the stack is empty
def is_empty(self):
return len(self.stack) == 0
# Get the current size of the stack
def size(self):
return len(self.stack)
Explanation of Code:
Example Usage
# Creating a stack object
my_stack = Stack()
# Pushing elements onto the stack
my_stack.push(10) # Stack is now [10]
my_stack.push(20) # Stack is now [10, 20]
my_stack.push(30) # Stack is now [10, 20, 30]
# Output the current stack
print("Current Stack:", my_stack.stack)
# Peek the top element
print("Top Element:", my_stack.peek()) # Output: 30
# Pop an element from the stack
print("Popped Element:", my_stack.pop()) # Output: 30
print("Stack After Pop:", my_stack.stack) # Stack is now [10, 20]
# Check if the stack is empty
print("Is Stack Empty?", my_stack.is_empty()) # Output: False
# Get the size of the stack
print("Stack Size:", my_stack.size()) # Output: 2
Output:
Current Stack: deque([10, 20, 30])Top Element: 30Popped Element: 30Stack After Pop: deque([10, 20])Is Stack Empty? FalseStack Size: 2
Explanation:
In Python, the queue module provides a FIFO (First-In-First-Out) queue implementation, but it can also be used to implement a stack by adjusting how we interact with the queue.
Specifically, we can use the LifoQueue class in the queue module. This class behaves like a stack and follows the Last-In-First-Out (LIFO) principle.
The main advantage of using the queue module is that it is thread-safe, meaning it can be used in multi-threaded environments where multiple threads interact with the stack concurrently.
Here’s how you can implement a stack using the queue.LifoQueue class:
import queue # Import the queue module
class Stack:
def __init__(self):
self.stack = queue.LifoQueue() # Create a LifoQueue object for stack
# Push operation: Adds an element to the stack
def push(self, value):
self.stack.put(value)
# Pop operation: Removes the top element from the stack
def pop(self):
if not self.is_empty():
return self.stack.get()
else:
return "Stack is empty!"
# Peek operation: Returns the top element without removing it
def peek(self):
if not self.is_empty():
temp_stack = []
# Move all items to a temporary stack
while not self.stack.empty():
temp_stack.append(self.stack.get())
top_element = temp_stack[-1]
# Push items back into the original stack
for item in temp_stack:
self.stack.put(item)
return top_element
else:
return "Stack is empty!"
# Check if the stack is empty
def is_empty(self):
return self.stack.empty()
# Get the current size of the stack
def size(self):
return self.stack.qsize()
Explanation of Code:
Example Usage
# Creating a stack object
my_stack = Stack()
# Pushing elements onto the stack
my_stack.push(10) # Stack is now [10]
my_stack.push(20) # Stack is now [10, 20]
my_stack.push(30) # Stack is now [10, 20, 30]
# Output the current stack
print("Current Stack:", [item for item in list(my_stack.stack.queue)])
# Peek the top element
print("Top Element:", my_stack.peek())
# Pop an element from the stack
print("Popped Element:", my_stack.pop())
print("Stack After Pop:", [item for item in list(my_stack.stack.queue)])
# Check if the stack is empty
print("Is Stack Empty?", my_stack.is_empty())
# Get the size of the stack
print("Stack Size:", my_stack.size())
Output:
Current Stack: [10, 20, 30]Top Element: 30Popped Element: 30Stack After Pop: [10, 20]Is Stack Empty? FalseStack Size: 2
Explanation:
A singly linked list is useful for implementing a stack because it allows dynamic memory allocation. This means we can add or remove elements without needing to resize or shift them as we do with arrays or lists.
Let’s start by implementing the stack using a singly linked list.
# Define a Node class to represent each element in the linked list
class Node:
def __init__(self, data):
self.data = data # Store the data
self.next = None # Initialize the next pointer to None
# Define the Stack class that uses a singly linked list
class Stack:
def __init__(self):
self.top = None # Initialize the stack with no elements
# Push operation: Adds an element to the top of the stack
def push(self, value):
new_node = Node(value) # Create a new node with the given value
new_node.next = self.top # Point the new node to the current top of the stack
self.top = new_node # Move the top pointer to the new node
# Pop operation: Removes the top element from the stack
def pop(self):
if not self.is_empty():
popped_value = self.top.data # Get the data of the top node
self.top = self.top.next # Move the top pointer to the next node
return popped_value # Return the popped value
else:
return "Stack is empty!"
# Peek operation: Returns the top element without removing it
def peek(self):
if not self.is_empty():
return self.top.data # Return the data of the top node
else:
return "Stack is empty!"
# Check if the stack is empty
def is_empty(self):
return self.top is None # Return True if stack is empty, else False
# Get the size of the stack
def size(self):
current = self.top # Start from the top node
count = 0
while current:
count += 1 # Count the nodes
current = current.next # Move to the next node
return count # Return the size of the stack
Explanation:
Example Usage
# Create a stack object
my_stack = Stack()
# Push elements onto the stack
my_stack.push(10)
my_stack.push(20)
my_stack.push(30)
# Peek the top element
print("Top Element:", my_stack.peek())
# Pop an element from the stack
print("Popped Element:", my_stack.pop())
# Check the size of the stack
print("Stack Size:", my_stack.size())
# Check if the stack is empty
print("Is Stack Empty?", my_stack.is_empty())
Output:
Top Element: 30Popped Element: 30Stack Size: 2Is Stack Empty? False
Explanation:
A stack program in Python is a data structure that follows the Last In, First Out (LIFO) principle. It allows you to add and remove elements in a specific order. You can implement a stack using lists, collections.deque, or linked lists.
In Python, a stack allows you to add elements using append() and remove elements using pop(). For example, stack = [] adds elements to the stack, and stack.pop() removes the top element.
The basic operations in a stack include push (adding an element), pop (removing the top element), peek (viewing the top element without removing), and is_empty (checking if the stack is empty).
You can implement a stack in Python with a list by using append() to add items and pop() to remove items. For example, stack = [] and stack.append(1) pushes an element, while stack.pop() removes the top element in a stack program in Python.
Yes, you can use collections.deque for stack in Python with example. It is well-suited for stack operations since it allows efficient appending and popping from both ends, providing better performance for stack program in Python.
In a stack program in Python, both lists and collections.deque allow adding and removing elements. However, collections.deque is optimized for stack operations, offering more efficient performance, particularly when you frequently add or remove elements from the stack.
A stack in Python with example can also be implemented using the queue.LifoQueue class from the queue module. It mimics stack behavior with methods like put() for adding elements and get() for removing elements, making it a suitable choice for stack programs in Python.
A singly linked list for stack implementation allows dynamic memory allocation. This means you don't need to predefine the size of the stack, making it more memory-efficient for larger datasets.
Yes, Python stacks, whether implemented using lists or linked lists, grow dynamically as needed. Lists grow automatically, and in a linked list, new nodes are added without resizing the entire structure.
When you try to pop an element from an empty stack, you get an IndexError with a list-based stack. To avoid this, check if the stack is empty using is_empty() before popping.
To check if a stack is empty in Python, use if not stack for lists or stack.empty() for a queue.LifoQueue. If the stack is empty, these expressions return True.
Take our Free Quiz on Python
Answer quick questions and assess your Python knowledge
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.
Author