Tuples

Flash and JavaScript are required for this feature.

Download the video from iTunes U or the Internet Archive.

Description: This in-class question demonstrates tuples in Python, including the difference between tuples and strings.

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.

PROFESSOR: All right, we've got some good competition here. So let's actually work through it.

So I have a function called always sunny and it's going to take in two variables right, t1 and t2. And I'm calling it with cloudy and cold.

So when I do my function call, t1 is going to be equal to cloudy. These are strings but I'm not going to bother putting the quotes. And t2 is equal to cold comma. So remember what I said, with a comma it's a tuple, without a comma it's a string.

So t1 is actually going to be a string. And t2 is actually a tuple. OK. So that's the first sort of trick to this question.

So I've made my function call and I've assigned t1 and t2 to be those two values. So the next line is sun is equal to sunny comma sun. So sun is going to be this tuple of two strings.

The next line is figuring out what first is. So first is going to be-- so I'm looking at my t1 here, it's a string. The fact that I have parentheses doesn't actually make a difference when I'm talking about strings. Like that.

So when I'm indexing into a string, t1 at position 0 actually just gives me a C because it's a string not a tuple. And t2 up position zero says, OK well, this is a tuple that contains only one element. That element being at position 0, and that element is the string, cold.

So this is a tuple. So I'm taking everything right before the first comma. And that happens to be just the one element that's in there. So this is just the string C cold. And then I'm returning here a tuple. And the tuple I'm returning is sun at position 0, so that's just sunny comma.

Just doing what's in here. And then first, and first was this string, C cold.

So really the important thing about this example was to make sure that you understand the difference between what a string is and what a tuple is.

Free Downloads

Video


Caption

  • English-US (SRT)