In this tutorial, you’ll learn how to implement a Python stack. You’ll see how to recognize when a stack is a good choice for data structures, how to decide which implementation is best for a program, and what extra considerations to make about stacks in a threading or multiprocessing environment.
Have you heard of stacks and wondered what they are? Do you have the general idea but are wondering how to implement a Python stack? You’ve come to the right place!
In this tutorial, you’ll learn:
This tutorial is for Pythonistas who are comfortable running scripts, know what a list
is and how to use it, and are wondering how to implement Python stacks.
A stack is a data structure that stores items in an Last-In/First-Out manner. This is frequently referred to as LIFO. This is in contrast to a queue, which stores items in a First-In/First-Out (FIFO) manner.
It’s probably easiest to understand a stack if you think of a use case you’re likely familiar with: the Undo feature in your editor.
Let’s imagine you’re editing a Python file so we can look at some of the operations you perform. First, you add a new function. This adds a new item to the undo stack:
You can see that the stack now has an Add Function operation on it. After adding the function, you delete a word from a comment. This also gets added to the undo stack:
Notice how the Delete Word item is placed on top of the stack. Finally you indent a comment so that it’s lined up properly:
You can see that each of these commands are stored in an undo stack, with each new command being put at the top. When you’re working with stacks, adding new items like this is called push
.
Now you’ve decided to undo all three of those changes, so you hit the undo command. It takes the item at the top of the stack, which was indenting the comment, and removes that from the stack:
Your editor undoes the indent, and the undo stack now contains two items. This operation is the opposite of push
and is commonly called pop
.
When you hit undo again, the next item is popped off the stack:
This removes the Delete Word item, leaving only one operation on the stack.
Finally, if you hit Undo a third time, then the last item will be popped off the stack:
The undo stack is now empty. Hitting Undo again after this will have no effect because your undo stack is empty, at least in most editors. You’ll see what happens when you call .pop()
on an empty stack in the implementation descriptions below.
#python #developer