Python single variable assignment, change and invariance of string assignment

I wrote an article about a trap of '=' in list objects in python
. Today, when a classmate who was learning python was discussing the problem with me, we expanded this problem a bit.

We know that for a list variable, assignment is equal to the transfer of the address, then modifying the original variable will also reflect the new variable that is assigned, as follows:

>>> a=[2]
>>> b=a
>>> a.append(3)
>>> b
[2, 3]

So, is this still the case for a single variable? In fact it is not, as follows:

>>> a=2
>>> b=a
>>> a=3
>>> b
2

Why would it be different? Isn't assignment in python the transfer of the address of an object in memory?
In fact, in the third part above,
a=3 A new object has been generated, that is, 3 is assigned to a new address, which is passed to the a variable, and the previous address holds 2 It still exists under the variable of b, so b has not changed.

Likewise, what about strings? I thought, isn't a string actually a list, so it should be the same as a list, and the experimental results are slapped in the face again:

b='dddd'
>>> a=b
>>> b=b+'111'
>>> b
'dddd111'
>>> a
'dddd'

Nothing has changed! Here's why.

Think about it for a while and think of this sentence, strings in python are immutable.

This means that 'dddddd'+'111' produces a new object like a single number.
So this is the result.

Guess you like

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