Wednesday, November 5, 2008

Immutability or mutability

As a programmer I develop many of application,using Java,C++,Python and Ruby.Today I want to talk about the "mutability" in these different language.Let's begin with Python language,Python is a dynamic language different to Java or C++.but as we talk about mutability,especially "string" of them.it's same.In python every object is is classified as mutable or immutable.or we can call them "changeable" or "unchangeable".For instance,We have a string "Spam",in Python you can create it as:
>>s="Spam"
"Spam"

In Java you can declare it as:
String s="Spam"

Now,the requirement is we want to access the sub-string of them:
#Python code
>>> s="Spam"
>>> s[0]
'S'
>>> s[0]="z"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

As you can see,we can access Python string as a sequence by use 'index'but if we want to assign a new value into the item of this string we got an exception,that means the string object in Python is immutable,it's similar to Java and C++,but it's different to Ruby.In Ruby you can assign a new value into the item of a string,and after assignment ,the original string object changed:
#Ruby code
irb(main):001:0> s="Spam"
=> "Spam"
irb(main):002:0> s[0]
=> "S"
irb(main):003:0> s[0]="z"
=> "z"
irb(main):004:0> s
=> "zpam" #the value of s has been changed.

That means the string object is mutable in Ruby.In terms of the core types, numbers, strings, and tuples are immutable; lists and dictionaries are not (they can be changed in-place freely).

No comments: