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

前端 未结 3 1403
孤独总比滥情好
孤独总比滥情好 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:56

    The two examples are not equivalent.

    By doing b = a you are telling b to point to the same list that a points to. If you change the list through a it will be changed even if introspected through b. There is only ever one list in memory.

    In the second example you are doing d = c which tells d to point to the same integer that c does, but then you are telling c to point to another integer. d does not know about it, and it is still pointing to the same integer that c used to point to.

    The equivalent example using lists to your second example will be

    a = [1, 2]
    b = a
    a = []
    print(a)
    # []
    print(b)
    # [1, 2]
    

    Check these visualizations:

    Your first example

    Your second example

    My example

提交回复
热议问题