Python references

前端 未结 5 1436
盖世英雄少女心
盖世英雄少女心 2020-11-29 10:00

Can someone explain why the example with integers results in different values for x and y and the example with the list results in x and y being the same object?

<         


        
相关标签:
5条回答
  • 2020-11-29 10:45

    The best explanation I ever read is here: http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables

    0 讨论(0)
  • 2020-11-29 10:46

    As the previous answers said the code you wrote assigns the same object to different names such aliases. If you want to assign a copy of the original list to the new variable (object actually) use this solution:

    >>> x=[1,2,3]
    >>> y=x[:] #this makes a new list
    >>> x
    [1, 2, 3]
    >>> y
    [1, 2, 3]
    >>> x[0]=4
    >>> x
    [4, 2, 3]
    >>> y
    [1, 2, 3]
    
    0 讨论(0)
  • 2020-11-29 10:53

    Because integers are immutable, while list are mutable. You can see from the syntax. In x = x + 1 you are actually assigning a new value to x (it is alone on the LHS). In x[0] = 4, you're calling the index operator on the list and giving it a parameter - it's actually equivalent to x.__setitem__(0, 4), which is obviously changing the original object, not creating a new one.

    0 讨论(0)
  • 2020-11-29 10:54

    That's because when you have a list or a tuple in python you create a reference to an object. When you say that y = x you reference to the same object with y as x does. So when you edit the object of x y changes with it.

    0 讨论(0)
  • 2020-11-29 10:57

    If you do y = x, y and x are the reference to the same object. But integers are immutable and when you do x + 1, the new integer is created:

    >>> x = 1
    >>> id(x)
    135720760
    >>> x += 1
    >>> id(x)
    135720748
    >>> x -= 1
    >>> id(x)
    135720760
    

    When you have a mutable object (e.g. list, classes defined by yourself), x is changed whenever y is changed, because they point to a single object.

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