Stacks in python
A stack is a data structure that is implemented using the First In Last Out Approach. A typical implementation of a stack would be trying to arrange three books all on the floor vertically(Book a, Book B and Book C respectively). We first pick book A and place it on the floor, then book B on top of Book A and finally Book C on top of A and B.
Popping
Now in order to get book A we need to take Book B and Book C off one by one before we can get to Book A again. This approach is called popping.
** Pushing **
To push an element on top of the stack simply means placing an element on top of the stack just like how we did when we were arranging our books vertically.
Enough theory let's write some code😎
Implementing this:
myStack = Stack()
Initialize the stack class
myStack.push("A")
myStack.push("B")
myStack.push("C")
Push three items onto the stack
Displaying the stack
['A', 'B', 'C']
Pop an item off the stack
print(myStack.pop())
Taking a peek at our stack
'B'
Let's break this down:
- We first created a class for our data structure and named it
Stack
- In our constructor function (
def __init__
), we created an empty list called items which will be called immediately we initialize an instance of theStack
class -
Push
- Since our values are held by a list, we can easily use the builtinappend
method on ouritems
list to add an element. -
Pop
- This uses the builtinpop
method to remove the first element on top of the stack. -
get_stack
- Returns a list of all items in the stack -
is_empty
- Compares theitems
list to an empty list and returns false or true if the list is empty or filled respectively. -
Peek
- Because a stack uses the First In Last Out approach, a peek at out stack should only show us the item on top of the stack.Hence we reverse the items list to reflect that...
You've successfully implemented a stack data structure in python🚀.
Grab a cup of coffee now becuase you're a genius🧠..
Top comments (0)