Python Set copy() method is used to copy the set but it’s a shallow copy. That means if we modify something in the copied set, changes are not reflected back in the original set.
set.copy()
Use “=” to copy a set, and modify the copied set, the changes are also reflected in the original set.
Set copy Python
Simple example code copy set and Add items to the set after copy.
n = {1, 2, 3, 4}
cn = n.copy()
# add 5 to the copied set
cn.add(5)
print('numbers: ', n)
print('new: ', cn)
Output:
Copy Set using = operator
n = {1, 2, 3, 4}
cn = n
# add 5 to the copied set
cn.add(5)
print('numbers: ', n)
print('new: ', cn)
Output:
numbers: {1, 2, 3, 4, 5}
new: {1, 2, 3, 4, 5}
Do comment if you have any doubts or suggestions on this Python set method topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.