-1
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.

khelwood
  • 55,782
  • 14
  • 81
  • 108
  • 2
    Does this answer your question? [Aren't Python strings immutable? Then why does a + " " + b work?](https://stackoverflow.com/questions/9097994/arent-python-strings-immutable-then-why-does-a-b-work) – Boris Verkhovskiy Jan 01 '20 at 21:20
  • 1
    The string is immutable. The variable `Word` is not immutable. It is the variable you are changing, not the string. – khelwood Jan 01 '20 at 21:41

2 Answers2

5

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.

Roland Smith
  • 42,427
  • 3
  • 64
  • 94
0

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.

TostMaster
  • 164
  • 2
  • 9