[Tutor] string immutability
Andreas Perstinger
andreas.perstinger at gmx.net
Mon Oct 24 21:07:49 CEST 2011
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
More information about the Tutor
mailing list