-
Book Overview & Buying
-
Table Of Contents
-
Feedback & Rating
Learn Python Programming - Fourth Edition
By :
The first fundamental distinction that Python makes about data is whether the value of an object can change. If the value can change, the object is called mutable, otherwise the object is called immutable.
It is important that you understand the distinction between mutable and immutable because it affects the code you write. Let us look at the following example:
>>> age = 42
>>> age
42
>>> age = 43 #A
>>> age
43
In the preceding code, on line #A, have we changed the value of age? Well, no. But now it is 43 (we hear you say...). Yes, it is 43, but 42 was an integer number, of the type int, which is immutable. So, what happened is really that on the first line, age is a name that is set to point to an int object, whose value is 42. When we type age = 43, what happens is that another int object is created, with the value 43 (also, the id will be different), and the name age is set to point to it. So, in fact, we did not change 42 to 43—we just pointed the name age to a different location, which is the new int object whose value is 43. Let us see the IDs of the objects:
>>> age = 42
>>> id(age)
4377553168
>>> age = 43
>>> id(age)
4377553200
Notice that we call the built-in id() function to print the IDs. As you can see, they are different, as expected. Bear in mind that age points to one object at a time: 42 first, then 43—never together.
If you reproduce these examples on your computer, you will notice that the IDs you get will be different. This is of course expected, as they are generated randomly by Python and will be different every time.
Now, let us see the same example using a mutable object. For this example, we will use the built-in set type:
>>> numbers = set()
>>> id(numbers)
4368427136
>>> numbers
set()
>>> numbers.add(3)
>>> numbers.add(7)
>>> id(numbers)
4368427136
>>> numbers
{3, 7}
In this case, we set up an object, numbers, which represents a mathematical set. We can see its id being printed and the fact that it is empty (set()), right after creation. We then proceed to add two numbers to it: 3 and 7. We print the id again (which shows it is the same object) and its value, which now shows it contains the two numbers. So the object’s value has changed, but its id is still the same. This shows the typical behavior of a mutable object. We will explore sets in more detail later in this chapter.
Mutability is a very important concept. We will remind you about it throughout the rest of the chapter.