assignment operator about list in Python

后端 未结 4 813
野趣味
野趣味 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 19:02

    BrenBam has a good explanation of what is going on. deepcopy a way to get around it:

    >>> from copy import deepcopy
    >>> list1 = ["Tom", "Sam", "Jim"]
    >>> list2 = deepcopy(list1)
    >>> list1[1] = "Sam's sister"
    >>> list1
    ['Tom', "Sam's sister", 'Jim']
    >>> list2
    ['Tom', 'Sam', 'Jim']
    

    Good programming style will make it rare to have to actually use deepcopy though.

提交回复
热议问题