Description: This in-class exercise demonstrates more simple list operations in Python, including indexing, extending, sorting, and deleting.
Instructor: Dr. Ana Bell
The following content is provided under a Creative Commons license. Your support will help MIT OpenCourseWare continue to offer high-quality educational resources for free. To make a donation or view additional materials from hundreds of MIT courses, visit MIT OpenCourseWare at ocw.mit.edu.
ANA BELL: Let's walk through it. We have three lists. L1 is equal to [re]. L2 is equal to [mi]. L3 is equal to [do]. L4 is equal to-- let's just do what it says here-- L1 plus L2. So it's going to be the list [re, mi]-- uh, yeah, mi.
Now, extend() is going to mutate the list. So that means L3 is going to be extended by whatever L4 is. So L3 is going to be-- OK, what did it have originally? It had do. And then, it's going to be extended by all of the elements inside L4, which is re, mi, like that. And once I've mutated it, the old version of L3 is gone, right? This is the L3 down here that I'm going to work with.
L3.sort() is going to sort alphabetically. So that's [do, mi, re]. Yep. And sort() also mutates the list. So the old version of the list I have is gone. del is going to also mutate the list. So it's going to look in L3, look at index 0, and it's going to delete that-- it's going to delete that element. So it's going to mutate L3. And it's going to be [mi, re], OK? And once again, I've mutated the list. So the old version's gone.
And lastly-- this is a tricky part-- I'm going to append, to my current L3, which looks like this, another list. So to L3, I'm appending another list. So this is going to be the list [fa, la], OK?
So [mi, re], and then the list [fa, la] is the answer, which is red-- no, sorry, blue. Good, you had me scared. OK. Perfect. So if you didn't get this, I would suggest you go through the Python tutor or you just trace it out by hand, just like I just did. And hopefully it'll be apparent, the more exercises you do with lists, what exactly is going on. OK.