











Python Set copy()
copy() in Python Sets
The copy() method returns the copy of the set in python.
When we use “=” sign to copy the set, if we modify the copied set then the changes are also reflected back in the original set. So here we have to create a shallow copy of the set such that when we modify something in the copied set, changes are not reflected back in the original set.


Syntax :
set2=set1.copy()
Return Type :
The copy() method returns a shallow copy of the set in python.
#copy() in python set
set1 = {1, 2, 3, 4, 5 }
print(“Set 1 : “,set1)
#all the values of set1 is copied to the set2
set2=set1.copy()
print(“Set 2 : “,set2)
#modifying set2
set2.add(10)
print(“After adding new element in set2”)
#changes is reflected in only set2 not in set1
print(“Set 1 : “,set1)
print(“Set 2 : “,set2)
Output : Set 1 : {1, 2, 3, 4, 5} Set 2 : {1, 2, 3, 4, 5} After adding new element in set2 Set 1 : {1, 2, 3, 4, 5} Set 2 : {1, 2, 3, 4, 5, 10}
In the above code the modification in copied set is only reflected in copied set.
See the below example to understand the difference between copy() and “=”.
# “=” in python set
set1 = {1, 2, 3, 4, 5 }
print(“Set 1 : “,set1)
#all the values of set1 is copied to the set2
set2 = set1
print(“Set 2 : “,set2)
#modifying set2
set2.add(10)
print(“After adding new element in set2”)
#changes is reflected in both set2 and set1
print(“Set 1 : “,set1)
print(“Set 2 : “,set2)
Output : Set 1 : {1, 2, 3, 4, 5} Set 2 : {1, 2, 3, 4, 5} After adding new element in set2 Set 1 : {1, 2, 3, 4, 5, 10} Set 2 : {1, 2, 3, 4, 5, 10}
Login/Signup to comment