- copy
- deepcopy
Shallow vs. Deep copy of lists
copy.copy() # shallow copy copy.deepcopy() # deep copy
examples/lists/shallow_copy.py
fruits = ['apple', ['banana', 'peach'], 'kiwi'] print(fruits) # ['apple', ['banana', 'peach'], 'kiwi'] print(fruits[0]) # apple print(fruits[1][0]) # banana salad = fruits[:] fruits[0] = 'orange' fruits[1][0] = 'mango' print(fruits) # ['orange', ['mango', 'peach'], 'kiwi'] print(salad) # ['apple', ['mango', 'peach'], 'kiwi']
examples/lists/deep_copy.py
from copy import deepcopy fruits = ['apple', ['banana', 'peach'], 'kiwi'] print(fruits) # ['apple', ['banana', 'peach'], 'kiwi'] print(fruits[0]) # apple print(fruits[1][0]) # banana salad = deepcopy(fruits) fruits[0] = 'orange' fruits[1][0] = 'mango' print(fruits) # ['orange', ['mango', 'peach'], 'kiwi'] print(salad) # ['apple', ['banana', 'peach'], 'kiwi']