元组是不可变的,列表是可变的。这意味着您可以更改列表的值,但不能更改元组的值。当您执行 t2 += (5,) 时,t2 中的值被复制并与您的元组 5 连接,这将创建一个新元组,然后将其存储在 t2 中。所以 t1 和 t2 现在不指向同一个对象。您可以通过查看对象的 id 来看到这一点
l1=[1,2,3,4]
l2=l1 #this points l2 to the same list as l1
print('l1:',l1, "ID:", id(l1))
print('l2:',l2, "ID:", id(l2))
l2.append(5) # this changes the list that l1 and l2 points to
print('l1:',l1, "ID:", id(l1))
print('l2:',l2, "ID:", id(l2))
t1=(1,2,3,4)
t2=t1 # this points t2 to the same tuple as t1
print('t1:',t1, "ID:", id(t1))
print('t2:',t2, "ID:", id(t2))
t2+=(5,) # This creates a new tuple and points t2 to it. t1 still points to the old tuple
print('t1:',t1, "ID:", id(t1))
print('t2:',t2, "ID:", id(t2))
输出
C:\Users\cd00119621\.virtualenvs\stackoverflow-yoix_gHB\Scripts\python.exe C:\Users\cd00119621\PycharmProjects\stackoverflow\stackoverflow.py
l1: [1, 2, 3, 4] ID: 56608872
l2: [1, 2, 3, 4] ID: 56608872
l1: [1, 2, 3, 4, 5] ID: 56608872
l2: [1, 2, 3, 4, 5] ID: 56608872
t1: (1, 2, 3, 4) ID: 56771760
t2: (1, 2, 3, 4) ID: 56771760
t1: (1, 2, 3, 4) ID: 56771760
t2: (1, 2, 3, 4, 5) ID: 25919192
Process finished with exit code 0