javapythondata-structuresdata-persistenceimmutablelist

how is original value from immutable variable accessed?


Immutable variable: a type of variable that stores it's original version if it is modified. Question: how do I access the older version of that variable in Python? or in Java? or any other languages that support this "persistent data structure?" or am I wrong about the definition of Immutable variables?

After I change a variable in, let's say ,python:

name = "nice name"
name = "bad name"

now, how do I retrieve the older value of var name?

Note: This question is different from the one it has been marked as duplicate of because, this question is about the memory location of variables and the other question is about the scope of variables.


Solution

  • In your example, name is a reference that points to a value.

    In your first line, name points to the immutable string "nice name".

    Then in your second line, you update name to point to a different immutable string "bad name".

    At this point, no variable references "nice name" - so it is no longer available.

    The str type is immutable because the "nice name" value itself cannot be updated. Any operation on a string will create a new block of memory to store the modified string in. In your example, "nice name" and "bad name" are stored in different blocks of memory - all that you are updating is the reference to the memory block.