stack | Python Glossary – Real Python
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:
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 added element ("c") is removed first, illustrating the LIFO behavior.
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)