I'm learning python for my class but I don't understand something. Changing the value of immutable data types causes them to be assigned to different addresses and the old values remain in the memory. Why is this so, even though it causes memory waste?
Asked
Active
Viewed 137 times
0
-
1"the old values remain in the memory" - if they're not referenced anymore, they will be garbage collected. – Thierry Lathuille Dec 09 '20 at 08:23
1 Answers
0
Generally, if you want to create something that is expected to be changed frequently, yes, it will waste memory if you use immutable objects. It's inefficient to make changes to them because you will need to copy them every time.
However, immutable objects are still very useful for many reasons. For example, for certain data structures, namely dictionaries and sets, immutable objects can be used as keys as they are always hashable (Note that immutable ≠ hashable).
key_str = "str" # Immutable
key_list = ["str"] # Mutable
dict_str = {key_str:0} # Works
dict_list = {key_list:0} # Doesn't work, because key_list isn't hashable
The fact that an object cannot be changed can also prevent it from being changed in place. For more information, you can refer to this post.

PIG208
- 2,060
- 2
- 10
- 25