View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Stack in Python

Updated on 22/01/20259,201 Views

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!”

Methods of Stack in Python

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.

1. Push  

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:

  • We created an empty list, which represents our stack.
  • We then used the append() method to add 10 and 20 to the stack.
  • The stack now contains [10, 20], with 20 at the top of the stack.

2. Pop  

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:

  • We used the pop() method to remove the top element (20).
  • After the operation, the stack contains only [10].

3. Peek  

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:

  • We accessed the top element (10) using the index -1, which points to the last item in the list.
  • Note that this doesn't remove the element from the stack; it only allows us to view it.

4. isEmpty 

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:

  • We used len(stack) to check the length of the stack.
  • If the length is 0, the stack is empty, and is_empty will return True.
  • Otherwise, it will return False.

“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!”

Implementation of Stack Using List in Python

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:

  • The Stack class contains a list self.stack which acts as the stack.
  • The push method adds an element to the stack using append().
  • The pop method removes the top element using pop(), checking first if the stack is not empty.
  • The peek method retrieves the top element without removing it, ensuring the stack isn't empty.
  • The is_empty method checks whether the stack is empty by checking if the list’s length is 0.
  • The size method returns the current size of the stack.

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:

  • We created an object my_stack of the Stack class.
  • We then pushed three numbers onto the stack: 10, 20, and 30. After each push, the stack grows.
  • We used the peek() method to view the top element (30) without removing it.
  • The pop() method removes and returns the top element (30), and the stack is updated to [10, 20].
  • The is_empty() method checks if the stack is empty (it’s not), and size() returns the current size of the stack (which is 2).

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

Implementation of Stack Using collections.deque 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:

  • self.stack = deque() initializes an empty deque object.
  • The push() method uses append() to add an element to the stack.
  • The pop() method removes and returns the last element using pop(), with a check to ensure the stack isn’t empty.
  • peek() returns the top element without modifying the stack.
  • The is_empty() method checks if the stack has any elements.
  • size() returns the number of elements currently in the stack.

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:

  • The deque() object my_stack is used for stack operations.
  • We pushed three elements (10, 20, 30) onto the stack.
  • We then used peek() to view the top element, which is 30.
  • The pop() method removed 30 from the stack, and the stack became [10, 20].
  • The is_empty() check confirmed that the stack is not empty, and size() showed that the stack now has two elements.

Implementation of Stack Using queue Module in Python

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:

  • self.stack = queue.LifoQueue() initializes an empty LifoQueue, which behaves as a stack.
  • push() adds an element to the stack using put().
  • pop() removes and returns the top element using get(), with a check for empty stack.
  • peek() retrieves the top element without removing it by temporarily moving elements to a temporary stack and returning the last element.
  • is_empty() checks whether the stack is empty using the empty() method.
  • size() returns the current size of the stack using qsize().

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:

  • The LifoQueue object my_stack is used for stack operations.
  • Three elements (10, 20, 30) were pushed onto the stack.
  • We used peek() to view the top element, which is 30.
  • The pop() method removed 30, and the stack is now [10, 20].
  • The is_empty() check confirmed that the stack is not empty.
  • The size() method confirmed that the stack has two elements.

Implementation of Stack Using a Singly Linked List in Python

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:

  • Node Class: This class represents an individual element of the stack, storing the value (data) and the reference to the next node (next).
  • Stack Class: This class contains the stack operations, such as:
    • push(): Adds a new element at the top of the stack by creating a new node and adjusting pointers.
    • pop(): Removes the top element by adjusting the top pointer.
    • peek(): Returns the top element without removing it.
    • is_empty(): Checks if the stack is empty by checking if the top pointer is None.
    • size(): Calculates the size of the stack by iterating through all nodes.

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:

  • The stack is initialized as empty (top = None).
  • We pushed three elements (10, 20, and 30) onto the stack. The stack now looks like: top -> 30 -> 20 -> 10 -> None.
  • The peek() method shows 30 as the top element without removing it.
  • The pop() method removes 30 from the stack, leaving 20 and 10.
  • The size() method returns the stack's size, which is 2 after one pop.
  • The is_empty() method confirms that the stack is not empty.

FAQ's

1. What is a stack program in Python?

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.

2. How does the stack work in Python with example?

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.

3. What are the operations in a stack program in Python?

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).

4. How can I implement a stack in Python with a list?

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.

5. Can I use collections.deque for stack implementation 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.

6. What is the difference between a list and collections.deque for stack 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.

7. How is a stack implemented using a queue module in Python?

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.

8. What is the advantage of using a linked list for stack implementation 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.

9. Can a stack in Python grow dynamically?

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.

10. What happens when I pop an element from an empty stack in Python?

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.

11. How do I check if a stack is empty in Python?

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.

image

Take our Free Quiz on Python

Answer quick questions and assess your Python knowledge

right-top-arrow

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

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.