赋值
赋值相当于指向同一个对象
a = [1, 2, 3, [4, 5, 6]]
a1 = a
a[0] = 666
a[3][0] = 999
print(a, id(a), id(a[-1]))
print(a1, id(a1), id(a1[-1]))
"""
[666, 2, 3, [999, 5, 6]] 2148022555264 2148018639168
[666, 2, 3, [999, 5, 6]] 2148022555264 2148018639168
"""
浅拷贝
列表是一个新的对象,子列表指向同一个对象
import copy
a1 = copy.copy(a)
a[0] = 666
a[3][0] = 999
print(a, id(a), id(a[-1]))
print(a1, id(a1), id(a1[-1]))
"""
[666, 2, 3, [999, 5, 6]] 1890298696320 1890294780224
[1, 2, 3, [999, 5, 6]] 1890298698560 1890294780224
"""
深拷贝
列表与子列表都相当与 一个新的对象
import copy
a = [1, 2, 3, [4, 5, 6]]
a1 = copy.deepcopy(a)
a[0] = 666
a[3][0] = 999
print(a, id(a), id(a[-1]))
print(a1, id(a1), id(a1[-1]))
"""
[666, 2, 3, [999, 5, 6]] 1793261048448 1793257132352
[1, 2, 3, [4, 5, 6]] 1793261050688 1793261048192
"""
其他方式
赋值切片相当于浅拷贝
a = [1, 2, 3, [4, 5, 6]]
a1 = a[:]
a[0] = 666
a[3][0] = 999
print(a, id(a), id(a[-1]))
print(a1, id(a1), id(a1[-1]))
"""
[666, 2, 3, [999, 5, 6]] 1522500571776 1522496655680
[1, 2, 3, [999, 5, 6]] 1522496863488 1522496655680
"""
列表的copy方法相当于浅拷贝
a = [1, 2, 3, [4, 5, 6]]
a1 = a.copy()
a[0] = 666
a[3][0] = 999
print(a, id(a), id(a[-1]))
print(a1, id(a1), id(a1[-1]))
"""
[666, 2, 3, [999, 5, 6]] 1890298696320 1890294780224
[1, 2, 3, [999, 5, 6]] 1890298698560 1890294780224
"""