The peek() method returns the value of the top-most item of the stack but doesn't remove the item from the stack. This video demonstrates how to use simple list indexing to accomplish this.
- We now have the basic functionality…for our stack class because…we have coded the push and pop methods.…So let's move on to these other three extra methods…if you will.…The next one is called peek.…And what this is going to do is show us…what the next value is that's ready to be popped.…So in other words, this should show us…the item that's on the top of the stack.…We want to return that item as well.…So all we need to do here is we just need to return…whatever value or whatever item…is in the last index of the list.…
So that would be self.items…and then we can index into the negative first position.…So I'm going to save this…and we'll go back to the terminal here,…fire up the interpreter.…I'm going to create another stack object…and I'll just push one thing onto it this time.…Going to stick with our apple example.…
So now if I call peek I expect it to show us apple.…And it does.…But what would happen if I tried to call peek…on an empty stack?…We can test that out ourselves.…So I'm going to pop off apple.…I can double check that my stack is empty now.…
- Abstract types and data structures
- Stacks as a linear abstract data type
- Creating the Stack class and its methods
- Adding items to the top and bottom of a stack
- Creating the Queue class and its methods
- Manipulating items in a queue
- Creating the Dequeue class and its methods
- Adding and removing items from a dequeue
Skill Level Advanced
Learning the Python 3 Standard Librarywith Kathryn Hodge2h 9m Intermediate
What you should know1m 26s
1. Abstract Data Types and Data Structures
2. The Stack
3. The Queue
4. The Deque
Next steps1m 43s
- Mark as unwatched
- Mark all as unwatched
Are you sure you want to mark all the videos in this course as unwatched?
This will not affect your course history, your reports, or your certificates of completion for this course.Cancel
Take notes with your new membership!
Type in the entry box, then click Enter to save your note.
1:30Press on any video thumbnail to jump immediately to the timecode shown.
Notes are saved with you account but can also be exported as plain text, MS Word, PDF, Google Doc, or Evernote.