1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
---
title: Mutability and Immutability in Python
description: "Mutable and immutable data types: what they are and how they work."
---
Consider this example:
```python
>>> 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 `s`.
How do you make `s` store `'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.
```python
>>> 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 `'hello'`.
{: class="has-dark-mode-background" }
When you call `s.upper()`, a new string, which contains the characters `'HELLO'`, gets created.
{: class="has-dark-mode-background" }
This happens even if you just call `s.upper()` without any assignment, on its own line:
```python
"hello".upper()
```
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 `'HELLO'`.
{: class="has-dark-mode-background" }
Now we can say that `'HELLO'` is stored in the `s` variable.
Then, because no variables refer to the _object_ `'hello'`, it gets eaten by the garbage collector.
{: class="has-dark-mode-background" }
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.
|