assignment operator about list in Python

后端 未结 4 814
野趣味
野趣味 2021-01-19 18:02

I am a beginner in Python, I cannot understand assignment operator clearly, for example:

list1 = [\"Tom\", \"Sam\", \"Jim\"]
list2 = list1

4条回答
  •  时光取名叫无心
    2021-01-19 18:59

    You're right, they aren't the same. Assignment to a bare name in Python (name = ...) is a different operation than assignment to anything else. In particular it is different from item assignment (name[0] = ...) and attribute assignment (name.attr = ...). They all use the equal sign, but the latter two are manipulable with hooks (__setitem__ and __setattr__), can call arbitrary code, and are generally under the control of the programmer. Assignment to a bare name is not under the control of the Python programmer. You can't affect what it does; it always just binds the right hand side to the name on the left hand side.

    This can be confusing, because people are used to thinking that the equals sign is what makes an "assignment". But in Python, in order to understand what operation is taking place, you really have to look on the left of the equals sign and see what kind of thing is being assigned to.

提交回复
热议问题