Simple Lists

Flash and JavaScript are required for this feature.

Download the video from iTunes U or the Internet Archive.

Description: This in-class question demonstrates basic list operations in Python.

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 owc.mit.edu.

ANA BELL: So we have a list L, originally, [life, answer, 42, 0]. In this example, if you don't know Hitchhiker's Guide to the Galaxy, that's why 42 is important. As a scientist, if I didn't at least one example with the number 42, I'd probably hear about it. So here it is.

OK, so we have this original list L, which contains the string "life", the string "answer", the number 42, and the number 0. Here, I'm writing a loop that iterates over every element directly in L, right? So originally, thing is going to be string "life", then, thing is going to be the string "answer", then, thing is going to be the number 42. And so what am I doing inside the loop as I'm iterating?

Well, if thing is equal to 0, then I'm going to do this. And otherwise, I'm going to do this. So for the first two iterations when thing is equal to "life" or "answer", I'm not doing anything. As soon as I hit 42 though, I'm saying, L, at position 1, is going to get this value here, OK?

So when I've iterated over this element here, I'm saying L, at position 1, I'm going to change its value, which says, well, I'm going to keep "life" the same, but this is going to be "everything". And then we're keeping the rest the same, 42 and 0, because we're only modifying L at position 1. As soon as we do that, we've finished with the loop when L was 42. And then we go through 0.

So now, thing takes on the value 0. And we say, if thing is equal to 0, well, we're good on that. L, at position thing, is equal to "universe". So L, at position 0, is equal to "universe". So that says, OK, I'm going to replace "life" with "universe". And then everything else stays the same-- 42 and 0, OK? So that would be my answer, [universe, everything, 42, 0]. Great, that's the majority. Good job.

Free Downloads

Video


Caption

  • English-US (SRT)