Python learning--2.7 immutable objects

str is an immutable object while list is a mutable object.
For a mutable object, such as a list, when you operate on the list, the content inside the list will change, such as:

>>> a = ['c', 'b', 'a']
>>> a.sort()
>>> a
['a', 'b', 'c']

And for immutable objects, such as str, what about str:

>>> a = ['c', 'b', 'a']
>>> a.sort()
>>> a
['a', 'b', 'c']

Although the string has a replace() method, it does change to 'Abc', but the variable a is still 'abc' in the end, how should we understand it?
Let's first change the code to the following:

>>> a = 'abc'
>>> b = a.replace('a', 'A')
>>> b
'Abc'
>>> a
'abc'

Always keep in mind that a is a variable and 'abc' is a string object! Sometimes, we often say that the content of object a is 'abc', but it actually means that a itself is a variable, and the content of the object it points to is 'abc'.
Therefore, for immutable objects, calling the object itself , without changing the contents of the object itself. Instead, these methods create new objects and return them, thus guaranteeing that immutable objects themselves will always be immutable.
A dict using a key-value storage structure is very useful in Python. It is important to choose immutable objects as keys. The most commonly used keys are strings.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325770571&siteId=291194637