Python references

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

提交回复
热议问题