Understanding Mutable vs Immutable Types
00:00
So an important first step is to understand the difference between these two words: mutable and immutable. You can launch Python and we can use the same list team
that has Jason, Matt, Caitlin, and Mark, or whoever you want to put in it.
00:15
Now, a list in Python is mutable. What does this mean? This means that if I want to change one member of the team, for example, I want to say team[1]
, which gives me Matt.
00:28 I want, however, this to be Trevor. So there’s been a change, Matt has left the team for some reason, and Trevor has joined, and this is perfectly fine. You can see that now the same list has Jason, Trevor in second place, and then Sarah, Caitlin, and Mark in exactly the same place.
00:44
However, if team
was a tuple, in this case, the same names, but this is a tuple, a reminder that the parentheses are not needed to create a tuple.
00:53 I’m using them here to make it clear that this is a tuple. But you could simply put the strings with commas; it’s the commas that make a tuple.
01:00
If I try to change the second item in team
, which is now a tuple, I want to remove Matt and put Trevor,
01:08 I get a TypeError. Python tells me that the tuple object does not support item assignment, which means I cannot take an existing element in the tuple and replace it with something else.
01:21 And this is the key difference between a tuple and a list. A tuple is immutable. Once you create the tuple, you cannot change any of its elements. You cannot add elements, you cannot remove elements, you cannot replace any of them. With the list, however, which is mutable, you can make any change you want.
01:40
So let’s create team
as a list to make sure it’s the one with the square brackets, and you can, for example, add a new member to the team by using .append()
.
01:49 Let’s say Kate has joined the team, and this is perfectly fine because a list is mutable, therefore I can add new values to it. I can also remove an element.
02:03 For example, if I want to remove Jason who’s left the team, that is also possible.
02:08 I cannot do any of these operations with a tuple, because with the tuple, once you create the tuple, you cannot make any changes to it.
02:19 So here’s a quick summary of this lesson. You can change the contents of a mutable object, such as a list. In this case, there’s a team, and we’re replacing Matt with Trevor.
02:32 However, you can’t make changes to the contents of an immutable object such as a tuple. In this case, you try to remove Matt and replace him with Trevor, and you get a TypeError.
Become a Member to join the conversation.