Tuples
- 02:13
Understand the difference between tuples and lists in Python.
Downloads
No associated resources to download.
Transcript
Before we move on to the next section, I wanna make a brief note on an object type called tuples. And we're not gonna use them very much, but there's one important distinction between a tuple and a list that you need to know before we continue. So, a tuple is going to be very similar to a list as you can see here, except it's enclosed within parentheses instead of square bracket. So I've defined tuple 1 and tuple and list one, each of which contain the integer one through five. And when I print those, they're gonna look almost the same except for the symbols on the outside of the tuple and on the outside of the list. Now, if I want to update that first object in list one, then as we just looked at, all I have to do is write the name of the list and then the index for the object that I want to change and use the equal symbol to assign a new object to that position. So let's say I wanna change it to 10. Now I can print my list and my one has updated to 10 very easy like you're familiar with already. However, if I want to do that with a two pull, I'm going to run into a problem.
I can call that object with the same index, but if I try and change it, I'm gonna have an issue.
So I get this error. It says, tuple object does not support item assignment, and that's because tuple are immutable. That means that you cannot change the objects in a tuple. Now, we're not going to use these very much in our code, but I wanna point this out to you in case later on in the course you're trying to change something in a list. You're trying to change an object in a list, but you're not able to do it for some reason. It seems like no matter what you try to do, you can't change the object in your list. If you're having that problem, go back and make sure that your list is actually a list and closed in square brackets and not a tuple enclosed in parentheses, because if you enclosed what you wanted to be a list in parentheses, it's going to be a tuple and you're not going to be able to change any of the objects. So be aware of that.