Python references

前端 未结 5 1452
盖世英雄少女心
盖世英雄少女心 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: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]
    

提交回复
热议问题