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)
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.

Advertisements

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:

WordPress.com Logo

You are commenting using your WordPress.com 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: