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.
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😎
myStack = Stack()
Initialize the stack class
Push three items onto the stack
Displaying the stack
['A', 'B', 'C']
Pop an item off the stack
Taking a peek at our stack
Let's break this down:
- We first created a class for our data structure and named it
- In our constructor function (
def __init__), we created an empty list called items which will be called immediately we initialize an instance of the
Push- Since our values are held by a list, we can easily use the builtin
appendmethod on our
itemslist to add an element.
Pop- This uses the builtin
popmethod to remove the first element on top of the stack.
get_stack- Returns a list of all items in the stack
is_empty- Compares the
itemslist 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🧠..