Mutability and Immutability in Python
Consider this example:
>>> s = "hello" >>> s.upper() 'HELLO' >>> s 'hello'
This might break your expectations.
After all, you've called the
upper() method on
s, so why didn't it change? That's because strings are immutable: you can't change them in-place, only create new ones.
In this example,
.upper() just cannot change the string stored in
How do you make
'HELLO' instead of
'hello' then? That's possible.
Even though you can't change the original string, you can create a new one, which is like the old one, but with all letters in upper case.
In other words,
s.upper() doesn't change an existing string.
It just returns a new one.
>>> s = 'hello' >>> s = s.upper() >>> s 'HELLO'
Let's examine what's going on here.
At first, the variable
s refers to some object, the string
When you call
s.upper(), a new string, which contains the characters
'HELLO', gets created.
This happens even if you just call
s.upper() without any assignment, on its own line:
In this case, a new object will be created and discarded right away.
Then the assignment part comes in: the name
s gets disconnected from
'hello', and gets connected to
Now we can say that
'HELLO' is stored in the
Then, because no variables refer to the object
'hello', it gets eaten by the garbage collector.
It means that the memory reserved for that object will be freed. If that didn't happen, the 'garbage' would accumulate over time and fill up all the RAM.