List is an ordered collection of varied or similar objects. And so is a tuple!
You can access list elements by its index. We can say the same for tuple elements.
One could slice a list. We could slice a tuple as well.
List and tuple, both could be deleted.
So, where’s the difference between a list and a tuple?
The main difference between a list and a tuple is that of mutability. A list is mutable but a tuple is immutable.
See also: What is immutability?
Does that mean we can change a list? Can you change its second element to something else? Let’s try it out.
Looks like it’s true. What about a tuple though? Can it not be changed? Let’s give it a whirl.
Elements of a tuple cannot be reassigned.
Can you add an item to the list? You certainly can!
What if you want to add an element to a tuple?
As we see, tuple does not have the attribute ‘append’ so we cannot append an element to it. However,
Looks like you can add an element to a tuple?
Actually, no. You cannot add an element to the tuple. It appears in the above example that we appended an element ‘aeroplane’ to the tuple. However, what actually happened is that we created a new tuple object instead.
See the different ids? The tuple has a different id after we added a new element to it.
They look the same to me, can I just abandon tuple and use lists for everything?
Well, you could and it could work out just fine. But there are some pitfalls.
Let’s say, I have listed out a few things to do this Saturday.
And then I realize that I would like to do the same things on Sunday as well. Therefore, I assign Saturday’s list to ‘sunday’.
Perfect! So, now I have two variables with list of things I would like to do on Saturday and Sunday. But then it hits me. Instead of calling mom on Sunday, I should call my Dad.
So, let’s fix it.
That should do it. Let’s see what I am going to do on Saturday and Sunday.
Wait, what? I thought I should call dad on just Sunday?
When I assigned ‘sunday’ to ‘saturday’, I did not actually create a new list. I pointed ‘sunday’ to to the same object(list) that ‘saturday’ was pointing. So, when I changed ‘sunday’, I was changing the same object that both ‘saturday’ and ‘sunday’ was pointing to.
Had I used tuples instead of list, I would not have run into this problem since tuples are immutable and I would have to have created a new object for Sunday.
So a rule of thumb is that, tuple should be used when you want to write-protect the data.