set copy() in python


In this tutorial, we are going to learn about the copy method set data structure. Let's see it in detail.

The method copy is used to get a shallow copy of a set.

Let's see different examples to under normal and shallow copy of a set.

Normal Copy

Follow the below steps and understand the output.

  • Initialize a set.
  • Assign the set to another variable with the assignment operator.
  • Now, add one more element to the copied set.
  • Print both sets.

You won't find any difference between. The assignment operator returns the set reference. both sets are pointing to the same object in the memory. So, whatever changes made to any of them will reflect in both of them.

Example

 Live Demo

# initialzing the set
number_set = {1, 2, 3, 4, 5}
# assigning the set another variable
number_set_copy = number_set
# changing the first value of number_set_copy
number_set_copy.add(6)
# printin the both sets
print(f"Set One: {number_set}")
print(f"Set Two: {number_set_copy}")

Output

If you run the above code, then you will get the following result.

Set One: {1, 2, 3, 4, 5, 6}
Set Two: {1, 2, 3, 4, 5, 6}

As we expected the first set also changed when we change the second set. How to avoid it?

We can use shallow to copy a set. There are multiple ways to shallow copy a set. One of the ways is to use the copy method of a set.

Example

Let's see the sample example with copy.

 Live Demo

# initialzing the set
number_set = {1, 2, 3, 4, 5}
# shallow copy using copy
number_set_copy = number_set.copy()
# changing the first value of number_set_copy
number_set_copy.add(6)
# printin the both sets
print(f"Set One: {number_set}")
print(f"Set Two: {number_set_copy}")

Output

If you run the above code, then you will get the following result.

Set One: {1, 2, 3, 4, 5}
Set Two: {1, 2, 3, 4, 5, 6}

If you see the output, you won't find any change in first set.

Conclusion¶

If you have any doubts regarding the tutorial, mention them in the comment section.

Updated on: 11-Jul-2020

188 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements