loading...
Cover image for Create a Stack Data Structure in Python..

Create a Stack Data Structure in Python..

nyamador profile image Desmond Updated on ・2 min read

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.

Stack Data Structure

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:

  1. We first created a class for our data structure and named it Stack
  2. In our constructor function ( def __init__), we created an empty list called items which will be called immediately we initialize an instance of the Stack class
  3. Push - Since our values are held by a list, we can easily use the builtin append method on our items list to add an element.
  4. Pop - This uses the builtin pop method to remove the first element on top of the stack.
  5. get_stack - Returns a list of all items in the stack
  6. is_empty - Compares the items list to an empty list and returns false or true if the list is empty or filled respectively.
  7. 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🧠..

Posted on by:

Discussion

markdown guide