Python copy() Function: Usage Explained
The copy() function is used to duplicate mutable data types like lists, dictionaries, and sets, and it returns a new object instead of a reference to the original object. Its usage is as follows:
- Copy the list:
original_list = [1, 2, 3, 4, 5]
copied_list = original_list.copy()
print(copied_list) # [1, 2, 3, 4, 5]
- Duplicate the dictionary.
original_dict = {'a': 1, 'b': 2, 'c': 3}
copied_dict = original_dict.copy()
print(copied_dict) # {'a': 1, 'b': 2, 'c': 3}
- Collection duplication
original_set = {1, 2, 3, 4, 5}
copied_set = original_set.copy()
print(copied_set) # {1, 2, 3, 4, 5}
Note: The copy() function only duplicates the object itself, so if the object contains mutable elements (such as lists, dictionaries, etc.), the copied object and the original object will share these mutable elements. Therefore, any modifications made to the mutable elements will affect both the original object and the copied object. To create a completely independent copy, you can use the deepcopy() function.