Python Set copy() Method with many examples

Python Set copy

Now, we are going to learn about the copy method here. As the name of the method says it is going to return a copy of the set. Let’s try to implement the copy method so that we can understand how we can use it.

Python Set copy

As you can see in the above program, we have a simple set, and then we use the copy method on the set. After that, we are trying to print the copy of the set, which is assigned to the variable copyset. You can try executing the program and checking the output.

But there is one thing. Let’s try to make use of the assignment operator, and do something like copyset = myset. Let’s see what happens when we try doing this.

As you can see in the above program, we have that simple tuple again, and in the next line, we are doing copyset = myset. Well, if we try to have a look at the output, the output would be similar to what we got with the copy method. But things are not like that. When we used the copy method, it returned a copy of that set. But here, when we are using the simple assignment operator, the copyset variable now points to the same set, as the myset variable. So, there are not two sets, but there are two reference variables, pointing to one set. Let’s try to make changes to the set.

As you can see, we tried to add element 60 to the set, and then we tried to print the set whose reference variable is copy set. On observing the output, we can find that the element was also there in the set referred to by the copyset variable. This is because there are no two sets, but there is one set and two reference variables for that set. So, now we know that the copy method returns the copy of the set.