Immutable vs. Mutable Sequences

Python sequences can either be mutable or immutable. Immutable sequences include strings and tuples whereas lists are mutable. After its creation, any element of an immutable sequence cannot be changed (replaced or deleted) whereas this is possible in case of mutable sequences. Immutable objects offer certain advantages: (usually) fixed and unchanged storage requirements, thread safety (since no one can change the sequence, all threads see the same thing), ease in handling multiple copies etc.

To test the immutability of strings, let's make a simple string:

In [29]:
strFruits='Apples, Oranges, Bananas, Coconuts, Lychee, Watermelon, Mangoes'

Let's try changing its first element:

In [30]:
strFruits[0]='a'
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-30-997e0c890273> in <module>()
----> 1 strFruits[0]='a'

TypeError: 'str' object does not support item assignment

As you can see that we get a TypeError exception indicating that we cannot change this. Let's print the string:

In [31]:
print strFruits
Apples, Oranges, Bananas, Coconuts, Lychee, Watermelon, Mangoes

No difference here!

Let's try the same thing with a tuple now:

In [32]:
tplFruits=('Apples','Oranges','Bananas','Coconuts','Lychee','Watermelon','Mangoes')
In [33]:
tplFruits[0]='Grapes!'
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-33-4a964d321784> in <module>()
----> 1 tplFruits[0]='Grapes!'

TypeError: 'tuple' object does not support item assignment

The same error! And also no change seen when we print this:

In [34]:
print tplFruits
('Apples', 'Oranges', 'Bananas', 'Coconuts', 'Lychee', 'Watermelon', 'Mangoes')

Now with a list:

In [35]:
lstFruits=['Apples', 'Oranges', 'Bananas', 'Coconuts', 'Lychee', 'Watermelon', 'Mangoes']
In [36]:
print lstFruits
['Apples', 'Oranges', 'Bananas', 'Coconuts', 'Lychee', 'Watermelon', 'Mangoes']

In [37]:
lstFruits[0]='Grapes'

No error! So we can change the contents of a list. Let's print it to see if we have, indeed, changed the list:

In [38]:
print lstFruits
['Grapes', 'Oranges', 'Bananas', 'Coconuts', 'Lychee', 'Watermelon', 'Mangoes']

In []: