assignment operator about list in Python

后端 未结 4 815
野趣味
野趣味 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:54

    BrenBarn is absolutely right about everything, but here is another way to look at it that might be easier to understand:

    Your first statement creates a list with those values, then makes list1 point to it. The second statement makes list2 point to exactly the same memory space as list1. (You can see this by running id on both of them after the second statement).

    At that point list1 and list2 are essentially both references to the same mutable list. When you change that list, list1 and list2 are still both referencing the same actual list and using either to access it will give you the same thing.

    I did a blog post about a related topic recently and Python Conquers the Universe also talks about a similar topic here.

提交回复
热议问题