why did one value change but the second value did not?

前端 未结 3 1401
孤独总比滥情好
孤独总比滥情好 2021-01-23 02:14
a = [ 1, 2 ]
b = a
a.append(3)
print(b) # shows [ 1 2 3 ] which means b changed

c = 4
d = c
c = 8
print(d) # shows 4 which means d did not change

Why

3条回答
  •  失恋的感觉
    2021-01-23 02:52

    It's all about if the object you assign is mutable or immutable.

    Simply put - mutable objects can be changed after they are created, immutable objects can't.

    Considering you have a variable a that is assigned to an object, when you point a new variable to the a variable, there are two possibilities:

    1. If an object is mutable -> you will just point to the same object with your new variable
    2. If an object is immutable -> you will assign a new object to your new variable.

    Your first case:

    • First you create a list a, which is a mutable object
    • Then you point with a second variable b to the same list object.
    • When you change value, you just change a mutable object, to which both variables are pointing.

    In second case:

    • First you assign a variable c to an immutable int=4 object.
    • Then you assign it to the second variable d.
    • And what happens next, is that you assign a new immutable int=8 object to the variable c.

    There is plenty of articles about what does it mean that an object is mutable, for example: https://medium.com/@meghamohan/mutable-and-immutable-side-of-python-c2145cf72747

提交回复
热议问题