使用' ='是否可以使用列表时是等号吗?即使myList已更改,下面的代码也会导致myOtherList的一致行为。使用.append()而不是' ='是否有任何隐藏的好处?直线等号?
myList=[1, 2, 3, 4, 5]
myOtherList=myList
myThirdList=[]
for each in myList:
myThirdList.append(each)
print myOtherList==myThirdList # True
myList=[]
print myOtherList==myThirdList # True
答案 0 :(得分:3)
==
和is
鉴于你的例子:
>>> myList = [1, 2, 3, 4, 5]
>>> myOtherList = myList
>>> myOtherList == myList
True
>>> myOtherList is myList
True
这表明这两个列表不仅包含相同顺序的相同值,它们实际上是相同的列表。鉴于:
>>> myThirdList = []
>>> for each in myList:
myThirdList.append(each)
>>> myList == myThirdList
True
>>> myList is myThirdList
False
它们现在是两个不同的列表,它们包含相同的值,顺序相同。