Junior
197
What is shallow copying?
Answer from AI
sobes.tech AI
Shallow copy creates a new complex object but does not create copies of the nested objects within it. Instead, it copies references to the nested objects of the original object.
Main points:
- Creates a new collection (list, dictionary, set).
- Elements of the new collection are references to the same objects as those in the original collection.
- Modifying nested objects in one copy will reflect in the other.
- Modifying the collection itself (adding/removing elements) in one copy will not affect the other.
Implementations:
.copy()method for lists, dictionaries, sets.copy.copy()function from thecopymodule.- Slice method
[:]for lists.
# Example with list
original_list = [[1, 2], 3]
shallow_copy_list = original_list.copy()
print(f"Original: {original_list}")
print(f"Shallow copy: {shallow_copy_list}")
print(f"Identity of nested lists: {original_list[0] is shallow_copy_list[0]}") # True - references are the same
original_list[0][0] = 99 # Changing nested list
print(f"After change original: {original_list}")
print(f"After change shallow copy: {shallow_copy_list}") # Change is visible in both copies
original_list.append(4) # Changing the collection itself
print(f"After append original: {original_list}")
print(f"After append shallow copy: {shallow_copy_list}") # Change only in original
# Example with copy.copy()
import copy
original_dict = {'a': [1, 2], 'b': 3}
shallow_copy_dict = copy.copy(original_dict)
print(f"Original: {original_dict}")
print(f"Shallow copy: {shallow_copy_dict}")
print(f"Identity of nested lists: {original_dict['a'] is shallow_copy_dict['a']}") # True
original_dict['a'][0] = 99 # Changing nested list
print(f"After change original: {original_dict}")
print(f"After change shallow copy: {shallow_copy_dict}") # Change is visible in both copies