Python Stack: Implementation and Operations

Python-Stack.jpg

Features like the undo button in a text editor or going back to a previous page while browsing are made possible with the use of a data structure called a stack, which works on the simple principle of Last In, First Out (LIFO). Python makes working with stacks easy by providing multiple ways to implement them. In this article, we will learn about the Python stack, with the implementation, operation, and its real-world use cases in detail.

What is a Stack in Python?

A stack is a data structure where the items are stored in the order of LIFO (Last In First Out), i.e., the last item you put in the stack is the first item that will come out of the stack. For example,

Stack: [1, 2, 3]

In the above stack, element 3 is added to the top of the stack hence, when you retrieve the element from the stack, element 3 will be the first element.

In the real world, in a stack of plates, you add the plates on top of each other, and you cannot remove a plate from the middle, i.e., you can only remove it from the top.

What is a Stack in Python
Master Python Programming
Learn the World's Most Versatile Language – From Basics to Advanced Applications!
quiz-icon

Characteristics of the Stack

Below are the characteristics of the Stack in Python.

  1. It works on the principle of Last In, First Out, i.e., the last item added is always the first one removed.
  2. It is a linear data structure, i.e., the elements are stored in a sequence, one after another.
  3. The element in the stack can be added or removed from the top of the stack, not directly from the middle of the stack.
  4. It has basic operations, like push, pop, peek, and is_empty.
  5. The size of the stack in Python is dynamic, i.e., they can grow and shrink accordingly if implemented using lists or linked lists.

Python Stack Operations

Below are some operations in the Stack in Python.

  1. Push: The push operation is used to add an element to the last of the stack. It is implemented using the append() method in a stack class.
  2. Pop: The pop operation is used to remove an element from the last of the stack. It is implemented using the pop() method in a stack class.
  3. Top or Peek: The Top or Peek operation is used to check the top element present in the stack without removing it. It is implemented using the stack[-1] in a list.
  4. Empty: The empty operation is used to check if the stack is empty. It is implemented using a manual check, like as not being stacked in a Python list.
  5. Size: The size operation returns the number of elements present in the stack. It is implemented using the built-in len(stack) function.

For example, in the image below, initially the stack was empty, and elements 1 and 2 are inserted using the push operation, and then the pop operation is used to retrieve element 2.

Python Stack Operations

Example:

Python

Output:

Python Stack example

Python Stack Implementation Using List

Python lists provide built-in methods that are used to implement the stack operations, such as append() and pop(). These methods allow you to implement the stack data structure.

Example:

Python

Output:

Python Stack Implementation Using List

Explanation: In the above Python code, we created an empty list named stack[]. The stack.append(10) is used to perform the push() operation, followed by the elements 20 and 30. Then the stack.pop() method is used to perform the pop() operation

Python Stack Implementation Using collections.deque

In Python, collections.deque provides a more efficient way to implement a stack as compared to lists, especially when the size of the stack is large. Deque allows fast addition and deletion of elements in the stack from both ends in O(1) time complexity.

Example:

Python

Output:

Python Stack Implementation Using collections.deque

Explanation: In the above Python code, the stack was implemented by importing deque from collections. The append() method is used to add elements to the stack, and the pop() method is used to remove elements from the top of the stack. The stack[-1] is used to peek at the topmost element in the stack.

Python Stack Implementation Using Linked Lists

A Linked List in Python is a linear data structure where the elements, called nodes, are connected to each other using pointers. Each node has data and a pointer to the next node.

  • Data stores the element.
  • Next stores the pointer to the next node.

Stacks can be implemented with the linked list and provide a dynamic memory allocation, i.e., non-fixed size like arrays, and efficient push and pop operations in O(1) time complexity.

Example:

Python

Output:

Python Stack Implementation Using Linked Lists

Explanation: In the above Python code, the stack is implemented using a linked list, where the Stack class operates on the pointer present at the top. The different functions push(), pop(), peek(), is_empty(), and display() are used to perform different operations.

Get 100% Hike!

Master Most in Demand Skills Now!

Python Stack Implementation Using a queue.LifoQueue

The Python queue module provides the class LifoQueue, which can be directly used as a stack. It follows the LIFO principle and provides thread-safe stack operations, which make it suitable for multithreading. The LifoQueue has built-in methods for stack operations.

Example:

Python

Output:

Python Stack Implementation Using a queue.LifoQueue

Explanation: In the above Python code, the stack was created with the help of a LifoQueue of size 5. The put() method is used to add the elements, and the get() method is used to retrieve the elements from the stack.

Implementation Ease of Use Push and Pop operations Dynamic Size Thread-Safe Memory Usage
List Very easy Fast Yes No Moderate
collections.deque Easy Very fast Yes No Efficient
Linked List Moderate Fast Yes No Higher
queue.LifoQueue Moderate Slightly slower due to locks Yes Yes Moderate

Advantages of Python Stack

Below are the pros of using a stack in Python:

  • Stacks in Python are very simple, i.e., you do not have to write a long code because data structures like list, deque, and LifoQueue already support the stack operations.
  • They have fast operations, i.e., adding and removing the elements from the stack happen from the top, due to which it takes a constant time of O(1).
  • The stack can be implemented in multiple ways, like lists, arrays, a deque, or even linked lists, depending on what your program needs.
  • It is very useful to solve real-world problems like checking balanced brackets, evaluating expressions, solving mazes (backtracking), and even managing function calls in Python itself.

Disadvantages of Python Stack

Below are the cons of using a stack in Python:

  • The stack has restricted access to the element, i.e., you can only access the top element of the stack, and cannot reach the middle element directly.
  • In Python, built-in lists and deques grow dynamically, so they do not throw overflow errors. However, if you try to remove an element from an empty stack, it will raise an underflow condition (e.g., IndexError).
  • When the stack is implemented with the linked list, each element holds a reference to the next node, which increases the memory consumption as compared to the list or arrays.
  • Python stacks have issues with large datasets, if implemented with lists or arrays, because they will allocate a new, larger block of memory (usually around double the size) and copy all existing elements, if more space is required.

Applications of Python Stack

Below are some real-world use cases of stacks in Python.

  • Stacks are used to evaluate the arithmetic expressions or convert expressions from infix to postfix to prefix notation.
  • They provide the functionality of undo and redo in text editors, drawing apps, or spreadsheets, as each action is pushed into the stack and the pop operation is used to retrieve the last action.
  • When a program calls a function, Python internally uses a call stack to keep track of function calls, which helps the program return to the correct point after a function finishes.
  • Browsers use a stack to visit the recently visited pages, by pressing the back button pops, allowing users to navigate backward.
  • It is used in many algorithms, like DFS, to keep track of the nodes that need to be visited, which helps to explore a path completely before moving to another.
Transition your career—start a free course today.
Become a Python Pro Today—No Fee Required
quiz-icon

Conclusion

From the above article, we learned that the Python stack is a linear data structure that follows the principle of LIFO. It allows adding and removing elements from only one end, making it very useful for problems that need last-in-first-out management. It can be implemented by many of the methods, lists, collections.deque, LifoQueue, and linked list. Stacks are widely used in real-world applications like undo/redo operations, expression evaluation, function call management, browser history, and backtracking problems. By choosing the right implementation, you can make your program both efficient and easy to manage.

If you want to learn more about Stack in Python, you can refer to our Python Course.

Useful Resources:

Python Stack – FAQs

Q1. What are stacks in Python?

A stack in Python is a linear data structure that stores elements in a specific order, allowing operations at one end only.

Q2. Are stacks LIFO or FIFO?

Stacks follow the LIFO (Last In, First Out) principle, where the last element added is the first one to be removed.

Q3. What is the main use of a stack?

The main use of a stack is to manage data in such a way that the last added element is accessed first.

Q4. How to create a stack?

A stack can be created in Python using a list, collections.deque, linked lists, or a queue.LifoQueue.

Q5. What is the difference between a stack and a queue?

A stack follows the LIFO principle, while a queue follows the FIFO (First In, First Out) principle.

Q6. What real-world examples use stacks?

Stacks are used in real-world applications such as undo/redo features in editors, browser history management, expression evaluation, function call management (call stack), and backtracking problems.

About the Author

Data Scientist | Technical Research Analyst - Analytics & Business Intelligence

Lithin Reddy is a Data Scientist and Technical Research Analyst with around 1.5 years of experience, specializing in Python, SQL, system design, and Power BI. Known for building robust, well-structured solutions and contributing clear, practical insights that address real-world development challenges.

EPGC Data Science Artificial Intelligence