Word='hello world'
Word=Word.upper()
Now in this code as per my understanding python strings are immutable so when I am reassigning what is actually happening? Can someone explain how python processes this scenario.
Word='hello world'
Word=Word.upper()
Now in this code as per my understanding python strings are immutable so when I am reassigning what is actually happening? Can someone explain how python processes this scenario.
Python "variables" (Word
in your case) are references to objects. The Python Language Reference therefore calls them "names" instead of "variables".
When you run Word.upper()
a new immutable string 'HELLO WORLD'
is created, and a reference to it is returned.
When you change the refence by the new assignment, the
reference count for the string 'HELLO WORLD'
is increased by one and that of the string 'hello world'
is reduced by one.
When a reference count of an object reaches zero, an object is garbage collected.
(Note that the above is slightly simplified for clarity.)
Read chapter 3 and 4 of the Python Language Reference, especially §4.2 Naming and binding to get a better understanding.
By calling the .upper() function, you do not change the string. If the function would alter the string itself, the assignment would not be necessary.
What happens here, is that by calling "hello world".upper()
, a completely new string is created, namely "HELLO WORLD"
. This new string is then assigned to your variable. The old string still remains in memory unaltered, but the variable doesn't point to it any longer.