The copy() method in Python returns a copy of the Set. We can copy a set to another set using the = operator, however copying a set using = operator means that when we change the new set the copied set will also be changed, if you do not want this behaviour then use the copy() method instead of = operator. We will discuss these with the help of examples.
Python Set copy() method Syntax
set.copy()
Parameters: None. This method doesn’t take any parameter.
Return value: Returns the copy of the given set
Copying a Set using = operator
In the following example we are copying a set to another set using = operator. The problem with this method is that if any of the set (old or new) is modified, the changes will reflect in both the sets. Here we have a set names
and we copied this set to a new set names2
.
After the copy using = operator, we have made changes in both the sets (added an element in new set and removed an element from old set), both the changes reflect in both the sets as shown in the following example. If you do not want this kind of behaviour and only want the set where you are making changes to be changed then use copy() method, which is discussed in the next section.
# A Set of names names = {"Steve", "Rick", "Negan"} names2 = names # adding a new element in the new set names2.add("Glenn") # removing an element from the old set names.remove("Negan") print("Old Set is:", names) print("New Set is:", names2)
Output:
Python Set copy() method example
Lets take the same example that we have seen above, however here we are copying the set using the copy() method. As you can see in the output that only the change that we have made to the old and new set reflect and both doesn’t share the same copy of the set as shown in the above example.
# A Set of names names = {"Steve", "Rick", "Negan"} # copying using the copy() method names2 = names.copy() # adding "Glenn" to the new set names2.add("Glenn") # removing "Negan" from the old set names.remove("Negan") # displaying both the sets print("Old Set is:", names) print("New Set is:", names2)
Output:
Leave a Reply