[Tutor] string immutability

Wayne Werner waynejwerner at gmail.com
Mon Oct 24 20:52:14 CEST 2011


On Mon, Oct 24, 2011 at 1:04 PM, Johan Martinez <jmartiee at gmail.com> wrote:

> Hi,
>
> I am struggling to understand Python string immutability. I am able to
> modify Python string object after initializing/assigning it a value. So how
> does immutability work? I am not following it. Sorry for really stupid
> question. Any help?
>
> <code>
>
> >>> s = "First"
> >>> print s.__class__
> <type 'str'>
> >>> print s
> First
> >>> s = "Second"
>

This is not actually modifying the string object. Unlike most other
programming languages where a variable refers to an actual location in
memory (usually), in Python the variable names the actual value.

So when you do s = "First" then you are telling python that you want to be
able to refer to the string "First" by the name/variable s.

When you execute s="Second" you are now telling python that instead of
referring to "First" you want the name 's' to refer to the string "Second".

If you try to modify the actual value of the string, you will raise an
exception:

>>> s = "First"
>>> s[0] = "T"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

HTH,
Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20111024/36472b45/attachment.html>


More information about the Tutor mailing list