[Tutor] string immutability

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


On Mon, Oct 24, 2011 at 2:07 PM, Andreas Perstinger <
andreas.perstinger at gmx.net> wrote:

> On 2011-10-24 20:04, Johan Martinez wrote:
>
>> Hi,
>>
>> I am struggling to understand Python string immutability. I am able to
>> modify Python string object after initializing/assigning it a value.
>>
>>   s = "First"
>>>>>  print s.__class__
>>>>>
>>>> <type 'str'>
>>
>>>  print s
>>>>>
>>>> First
>>
>>>  s = "Second"
>>>>>  print s
>>>>>
>>>> Second
>>
>
> Dave, Sander and Wayne have already explained why you aren't modifying
> string objects in your example.
> With the id()-function you can also see what is happening:
>
> >>> s = "First"
> >>> id(s)
> 3077110080L    # In CPython this is the memory address of the object
>               # with the name 's' (in your case "First")
> >>> s = "Second"
> >>> id(s)
> 3077110304L    # You see that 's' refers now to another address
> >>> id("First")
> 3077110080L    # But "First" is still on the same address as before
> >>> id("Second")
> 3077110304L    # And this proves that "Second" is at the address
>               # which 's' refers to
>
> Bye, Andreas
>

Great, that's really helpful Andreas.

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


More information about the Tutor mailing list