[Tutor] string immutability

Johan Martinez jmartiee at gmail.com
Mon Oct 24 21:17:08 CEST 2011


On Mon, Oct 24, 2011 at 1:52 PM, Wayne Werner <waynejwerner at gmail.com>wrote:

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


Thanks for the replies everyone - Steve, Dave, Sander and Wayne. I realized
my wrong understanding/interpretation after posting the message to the list,
which usually  happens most of the time with me!



jM.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20111024/d029b391/attachment.html>


More information about the Tutor mailing list