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

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

    The answer provided by @DeepSpace is a good explanation.

    If you want to check if two variables are pointing to the same memory location you can use is operator and to print them use id.

    >>> a=[1,2]
    >>> b=a
    >>> a is b
    True
    >>> id(a),id(b)
    (2865413182600, 2865413182600)
    >>> a.append(2)
    >>> a,b,id(a),id(b)
    ([1,2,2],[1,2,2],2865413182600, 2865413182600)
    >>> a=[1,2]
    >>> b=[1,2]
    >>> a is b
    False
    

提交回复
热议问题