Python 3リストの深いコピーと浅いコピー

7847 ワード

a = 1
b = a
a = 2
print(a, b)
print(id(a), id(b))
"""
    
2 1
1445293568 1445293536
"""

#                ,          
list1 = ["a", "b", "c"]
list2 = list1
list1.append("d")
print(list1, list2)
print(id(list1), id(list2))
"""
    
['a', 'b', 'c', 'd'] ['a', 'b', 'c', 'd']
1947385383176 1947385383176
"""

#    
list1 = ["a", "b", "c"]
list2 = list1.copy()
list1.append("d")
print(list1, list2)
print(id(list1), id(list2))
""" 
    :
['a', 'b', 'c', 'd'] ['a', 'b', 'c']
1553315383560 1553315556936
"""

#    ,        ,           
list1 = ["a", "b", "c", [1, 2, 3]]
list2 = list1.copy()
list1[3].append(4)
print(list1, list2)
print(id(list1), id(list2))
"""
    
['a', 'b', 'c', [1, 2, 3, 4]] ['a', 'b', 'c', [1, 2, 3, 4]]
1386655149640 1386655185672
"""

#    
import copy  
list1 = ["a", "b", "c", [1, 2, 3]]
list2 = copy.deepcopy(list1)
list1[3].append(4)
print(list1, list2)
print(id(list1), id(list2))
"""
    
['a', 'b', 'c', [1, 2, 3, 4]] ['a', 'b', 'c', [1, 2, 3]]
1452762592904 1452762606664
"""