Immutable objects: How does Python decide whether to create new one, or reuse an existing one?

Viewed 68

From the book:

 When an immutable object is updated, a new object is created instead.  

Consider the following code:

>>> text = "Python"
>>> enriched_text = text
>>> enriched_text += " is awesome!"  # at that point, new string is created (all good)
>>> original_text = enriched_text[0:6]  # revert it back to 'Python'
>>> id(original_text) == id(text)
False  # <--- (new object was created for truncated string)
>>> original_text = 'Python'  # assign it from scratch
>>> id(original_text) == id(text)
True   # <--- (somehow it rejects creating new one)

I tried same procedure with floats and long integers, behavior is the same. Any ideas?

Note: This is just an experiment of mine: I'm trying to learn how python works with the variables. Any good reference will also be appreciated. Thanks!

0 Answers
Related