l = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
l1 = l
l1.append('5')
print(l1,l)
print(id(l1), id(l), '\n')
l = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
l2 = l.copy()
l2.append('0')
print(l1, l)
print(id(l1), id(l), '\n')
s = 1
s1 = s
s1 = s1 + 1
print(s1, s)
print(id(s1), id(s), '\n')
输出:
['a', 'b', 'c', 'd', 'e', 'f', 'g', '5'] ['a', 'b', 'c', 'd', 'e', 'f', 'g', '5']
2735777866312 2735777866312
['a', 'b', 'c', 'd', 'e', 'f', 'g', '5'] ['a', 'b', 'c', 'd', 'e', 'f', 'g']
2735777866312 2735778356488
2 1
140731163595840 140731163595808
总结:
对一个变量赋值一个列表(list),该变量变成列表,且它与原列表一模一样,包括地址,修改它和修改原列表是等价的。
使用list.copy()创建一个新变量时,两个列表的内存地址不再一样,各自保持独立。