In Python, objects can be categorized into two types: mutable and immutable. Mutable objects can have their values changed after they are created, while immutable objects cannot. Understanding mutable objects and the concept of shallow copying is fundamental in Python programming, as it affects how changes to data structures are handled.
Mutable Objects
Mutable objects are those whose state or contents can be changed after creation. Common mutable objects in Python include:
•
Lists (list)
•
Dictionaries (dict)
•
Sets (set)
For example, if you create a list, you can add, remove, or change its elements:
my_list = [1, 2, 3]
my_list.append(4) # my_list is now [1, 2, 3, 4]
my_list[0] = 0 # my_list is now [0, 2, 3, 4]
Python
복사
Immutable Objects
Immutable objects, on the other hand, cannot be altered once they are created. Attempting to change an immutable object will result in the creation of a new object. Common immutable objects include:
•
Integers (int)
•
Floats (float)
•
Strings (str)
•
Tuples (tuple)
Shallow Copy
A shallow copy of an object is a new object which stores the reference of the original elements. This means that for compound objects (objects that contain other objects, like lists or dictionaries), the original and the copy will refer to the same nested objects. Changes to the contents of these nested objects in the original will affect the copy, and vice versa.
You can create a shallow copy using the copy method for lists or the copy module for other objects:
import copy
original_list = [[1, 2, 3], [4, 5, 6]]
shallow_copied_list = copy.copy(original_list)
# Modifying an element in a sublist affects both lists
original_list[0][0] = 'X'
print(shallow_copied_list) # Output: [['X', 2, 3], [4, 5, 6]]
Python
복사
In the example above, changing an element in one of the sublists of original_list also changes the same element in shallow_copied_list, because the shallow copy only copies the outer list structure, not the inner lists themselves.
Understanding mutable objects and shallow copies is crucial for managing data structures effectively in Python, especially when working with complex, nested objects where unintended modifications can lead to bugs.