Creating Stacks With .append()
00:12 A data type is a type along with a collection of operations to manipulate the type. An abstract data type is a specification of a data type in a particular language, but not specifying exactly how the code should be written to implement its operations.
00:57 So, what is a stack? Like the name suggests, a stack is a data structure where you can visualize it as items stored on top of other items. It’s often referred to as a Last-In/First-Out structure.
01:13 The first thing you put in becomes the bottom of the stack and it won’t be taken out until everything else is removed from on top of it. The two main operations of a stack are push to put a new item on the top of the stack and pop to remove the top item off of the stack.
So, let’s take a closer look at list’s
.pop() method. So create a list and now you will use the
.pop() method on it. The
.pop() can take an argument, which indicates which item from the list is to be removed.
.pop() method also returns that item to the calling agent, assuming that it’s intended to be used as it comes off out of the list. So if you call
.pop(1) on this list, the item in position
1 will be popped and returned.
So here is an implementation of the stack data structure, making use of
.pop(). Let’s take a closer look. I’ve called this file
list_stack because it’s the stack data type implemented using a list. It’s defined as a class, so it begins with the phrase
The empty list is created and saved to the attribute
._items. An underscore (
_) is used to indicate that this attribute should not be accessed directly, but that the stack should only be accessed through the methods that are provided.
And here are the implementations of the stack operations.
.append() is used to implement
.push(). You want the top of the stack to be at the end of the list, so pushing an element to the stack means it needs to be added, or appended, to the end of the list.
This is because popping off an empty stack will cause an error and you want the program to behave reasonably if that is attempted. The error you saw was an
IndexError, so if this operation results in an
IndexError, it will display
You see two other methods implemented here. When defining a class, it’s common to implement several of what are referred to as dunder methods, whose name begin and end with double underscores (
Here, it’s implemented the dunder method
.__len__() for length so that the
len() function can be used on a stack object to see how many elements are in the stack. And the dunder method
.__repr__() has been implemented to provide a way to represent this stack object in a print statement or in other contexts where its value can be displayed.
Become a Member to join the conversation.