Python for Fortran programmers 6: mutable and immutable
Before we deal with the “problem” of default values, we need to clearly understand what mutable and immutable objects are, because this is a concept that does not appear in Fortran.
Objects in Python can be mutable or immutable. This may seem pretty irrelevant. After all, what is the difference between:
a = 5 #immutable a = [1, 2, 3 ] #mutable
True, mutable objects have some methods such as
a.pop() that immutable objects don’t have. But again, you can think of workarounds:
b = (1, 2, 3) #an immutable tuple b = b[:-1] #all elements except the last one.
However it is important to realize that
b is now a new object (it has a different memory address) having the same name as the previous one, whereas
a remains the same object (same memory address) after the
pop method is called. You can check that by calling
id(b) before and after the assignments. When we modify a mutable object, the object remains the same, but when we “modify”
b, we create a new object:
a = [1, 2, 3] >>> id(a) 139878335741320 >>> a.pop() 3 >>> a [1, 2] >>> id(a) #the same as before 139878335741320 >>> b = (1, 2, 3) >>> id(b) 139878160519888 >>> b = b[:-1] >>> b (1, 2) >>> id(b) # a NEW object with the same name 139878160530536
Now we can deal with the surprising behaviour of default arguments.