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(a) and 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)
>>> a.pop()
>>> a
[1, 2]
>>> id(a) #the same as before
>>> b = (1, 2, 3)
>>> id(b)
>>> b = b[:-1]
>>> b
(1, 2)
>>> id(b) # a NEW object with the same name

Now we can deal with the surprising behaviour of default arguments.


Tags: , ,

About Ramon Crehuet

I'm a Computational Biochemist working at the IQAC institute of the Spanish National Research Council (CSIC)

One response to “Python for Fortran programmers 6: mutable and immutable”

  1. CAChemEorg says :

    A basic idea that helped me a lot was to think about the semantics. Tuples are useful when the id() has relevance. For example, from coordinates in mathematics, which even uses the same syntax: (x, y, z) are not comparable to (x,y) although you just popped the last “value”.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: