Happy Labour Day! Let’s code. (Coding Blog) — Week 5
Yo. Happy labour day everyone. Hope you spent the day well, and good luck to those of you starting school!
Today, we’ll be implementing our own stack!
A stack is an important data structure that uses a simple concept — first in, last out. Whatever you push to the top of you stack first, is the last to leave. A visual representation of a stack can be seen below (done by yours truly using good ol’ microsoft paint).

Now that we know what a stack is, let’s look at what operations can be used on a stack. The main two operations are push and pop. Push places a value on the top of the stack, pop takes it off and returns it. There’s also peek, which returns the top value of the stack without popping it, and lastly, there’s empty, which will return a boolean value describing whether the stack is empty.
Now that we know everything we need in our stack, let’s get to coding it!
First, we’ll create our class and our init function. This initializes our stack.

We will then make our empty function. This just returns True if it’s empty, and False if there are any values in our stack.

Next, we’ll create our push and pop functions. Push can be easily implemented using append() on our list, and pop can be implemented using the pop() function on our list. We have to remember to raise an exception if the stack is empty as well.

Lastly, we’ll make our peek function. Peek simply returns the top value of the stack. We also have to remember to raise an exception if the stack is empty for this function.

And we’re donezo! An easy stack that we created in just a few minutes in just 20 lines of code. You can add to it by adding other stack functions, such as min, max, length, and more.
Check out the code on GitHub.
We’ll be doing a cool problem next week (that may or may not use stacks (just kidding it definitely will)), so stay tuned!
Until next time ❤
