sec02 - Python Set Copy Guide: Difference Between copy() and Assignment, Is Deepcopy Needed?
スポンサーリンク

Key Considerations When Copying Python Sets

After copying a set using a statement like B = A, if you modify elements in either variable, the changes will also affect the other variable's output. This happens because both variables reference the same set object.

A = {1, 2, 3}

B = A
B.add(99)

print(A, id(A))   # {99, 1, 2, 3} 1724884493120
print(B, id(B))   # {99, 1, 2, 3} 1724884493120

How to Use Python's set.copy() Method (Shallow Copy)

Since sets do not maintain element order, you cannot use slicing like you would with a list. To safely copy a set, use the copy() method.

A = {1, 2, 3}

B = A.copy()
B.add(99)

print(A, id(A))   # {1, 2, 3} 1731857326912
print(B, id(B))   # {99, 1, 2, 3} 1731857326240

By using the copy() method, variables A and B reference different set objects. Therefore, modifying one variable, such as adding an element, does not affect the other.

スポンサーリンク

Is Deepcopy Necessary for Python Sets?

Sets cannot contain mutable objects as elements, and attempting to do so will result in an error at assignment. This applies not only when directly using lists as elements, but also in indirect cases, such as a list inside a tuple within the set.

Therefore, for sets, you do not need to consider nested cases, and performing a Deepcopy is unnecessary.

スポンサーリンク