stack
In Python, a stack is a data structure that follows the Last In, First Out (LIFO) principle. This means that the last element added to the stack will be the first one to be removed.
Imagine a stack of plates where you can only add or remove the top plate. In Python, you can implement a stack using a list, where you append elements to the list to push them onto the stack and use the .pop()
method to remove them from the top.
Stacks can be particularly useful in scenarios where you need to reverse items, backtrack operations, or manage a function call’s state, such as in recursive algorithms.
Example
Here’s a simple example of how you can use a list as a stack in Python:
>>> stack = []
>>> # Pushing elements onto the stack
>>> stack.append("a")
>>> stack.append("b")
>>> stack.append("c")
>>> stack
['a', 'b', 'c']
>>> # Popping elements from the stack
>>> stack.pop()
'c'
>>> stack
['a', 'b']
In this example, elements are added to the stack using the .append()
method and removed using .pop()
. The stack initially has three elements, and after popping, the last element added ("c"
) is removed first, illustrating the LIFO behavior.
Related Resources
Tutorial
Python Stacks, Queues, and Priority Queues in Practice
In this tutorial, you'll take a deep dive into the theory and practice of queues in programming. Along the way, you'll get to know the different types of queues, implement them, and then learn about the higher-level queues in Python's standard library. Be prepared to do a lot of coding.
For additional information on related topics, take a look at the following resources:
- Python's deque: Implement Efficient Queues and Stacks (Tutorial)
- How to Implement a Python Stack (Tutorial)
- Implementing a Stack in Python (Course)
By Leodanis Pozo Ramos • Updated June 24, 2025