The peek() method returns the value of the top-most item of the queue but doesn't remove the item from the queue. The video demonstrates how to use simple list indexing to accomplish this.
- [Instructor] We've covered the basic functionality…with enqueue and dequeue but what if we just want…to look at what the next item in…the queue is that's going to be removed next.…We can use our peek method for that.…And basically all we need to do is just we turn…the last item in the list because that last item…in the list is the item that's going to get removed next.…So in terms of code we can simply say…return self.items at the negative first index.…
We'll start with that.…So I saved the file, we'll go to the terminal…and we'll get the interpreter started.…I'll create my own queue object.…And let's try this just as the object is.…We haven't added anything to it yet…which means that items should be empty and it is.…So if we say my_q.peek we get an error.…List index out of range.…
So what's happening is we're trying…to access the negative first index…but we don't even have anything in the list to index into.…We can handle this situation in our code.…What we want to say is as long…as there are items in the list…
- 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 10m 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.