From the course: Python Data Structures: Stacks, Deques, and Queues
The push() operation - Python Tutorial
From the course: Python Data Structures: Stacks, Deques, and Queues
The push() operation
- [Instructor] In this video, we're going to dive deeper into the stack data structure in Python and specifically look at the push operation. So, first of all, let's recall what a stack is and how it works. Now, a stack is a linear data structure that follows the Last In First Out principle. This means that the last item that is added to the list is always the first one to be removed. So, let's have a look at how we can add an item to a stack. Now, in Python, we can use the append method to add an item to the end of the list, and we can treat this list as a stack. So, let's go ahead and create our own stack. And for this case, it would just be a set of four numbers: one, two, three, and four. Now, if we want to add in a number at the end, and in our case it's going to be five, we can go ahead and say stack.append, and then in brackets, five. Now, when we actually go ahead and print out this stack, it should print out the full list: one, two, three, four, and five. But what if we want to add an item to the top of the stack instead of at the end? Well, this is where the push operation comes in. For example, let's say now, if you want to add in a zero to start the list instead of at the end. If you go ahead and run this right now, it comes up with one, two, three, four, and zero, and not the desired output. So, we can go ahead and create a function in order to implement this new functionality. So, let's go ahead and say, define a new function, which is going to be called push. And then, we'll give it the parameters of stack and then item. And then, we'll go ahead and say stack.insert, which is a new keyword, and then we'll give that the parameters of zero and then item. Okay, so, now let's go ahead and call this function, and we can go ahead and say push, stack, and then zero. Now, our stack is basically what I seen over there, and our item is zero. So, now if we go ahead and run our stack, then it has pushed the zero to the start of the list. So using the insert method, we're able to add in the item, which is a zero to the start of the stack instead of at the end, and that's the push operation in a nutshell. The push operation is a powerful way to add items to the top of a stack in Python. Whether you're solving a problem that requires keeping track of information in reverse order or implementing an undue functionality in your code, using the push operation can help you achieve your goals.