2

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!

Ali Yılmaz
  • 1,657
  • 1
  • 11
  • 28
  • This only happens with short strings and small numbers - if you test with longer strings, you'll find the ids are different. There's some explanations [here](https://stackoverflow.com/questions/38189660/two-variables-in-python-have-same-id-but-not-lists-or-tuples). – sj95126 Oct 08 '21 at 14:54
  • In short, the implementation can decide whether a new object for the *literal* needs to be created, or if it can look for an equivalent object already in memory. – chepner Oct 08 '21 at 17:06
  • The important point here is: whether an existing object is reused or not is *not* a property of Python, but of a particular Python implementation. – chepner Oct 08 '21 at 17:08
  • An immutable instance cannot change and is thus completely distinguished from other instances by its value. Languages are free to reuse (intern, pointers) or copy an immutable instance at will because it makes no difference to the program. Therefore, you should compare *values* (e.g. `==`) to compare immutable instances. Python doesn't give you an easy way to leverage immutable reuse, though, there's no `immutable class` definition. – BatWannaBe Oct 08 '21 at 18:33

0 Answers0