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

前端 未结 3 1400
孤独总比滥情好
孤独总比滥情好 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
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题