Python Set Copy():

The copy() method creates a shallow copy of the set in python. Therefore, If we modify or add any data in the copied set, those modifications will not be reflected in the original set.

Method signature

The signature for the copy() method is as shown below. Here, copied_set is a shallow copy of the original set, whereas original_set contains data that we are copying.

copied_set = original_set.copy()

Method parameters and return type

  • The copy() method doesn’t take any parameters.
  • However, it returns a shallow copy of the original set.

Python Set Copy Examples:

Example 1: In this example, let us take a set original with set of numbers. The variable copied contains a copy of original set.

#Initializing the Set
original = {1,13,42,3,65}

# Creating copy of set
copied=original.copy()
#Printing both set
print("Original Set",original)
print("Copied Set",copied)

Output

Original Set {65, 1, 3, 42, 13}
Copied Set {65, 1, 3, 42, 13}

Example 2: In this example, let us take a skill set of two students. Firstly, We will initialize the data of the first student as “s1”. Then, we copy the same skill set using copy() method for another student “s2”.

In the meantime, If student s2 learns new skills say “python”. Hence, We have to add it using the add() method. As a result, these updates are done in the shallow copy only. Thus, the original set remains unchanged.

#Intializing the Set
s1 = {"C","C++","Java"}
# Creating copy of Original set
s2=s1.copy()
# Printing both the Set
print("Skills of student 1",s1)
print("Skills of student 2",s2)
# Adding skills to shallow copy of the Set
s2.add("Python")
#Printing again
print("Skills of student 1",s1)
print("Skills of student 2",s2)

Output

Skills of student 1 {'C', 'C++', 'Java'}
Skills of student 2 {'C', 'C++', 'Java'}
Skills of student 1 {'C', 'C++', 'Java'}
Skills of student 2 {'C', 'C++', 'Java', 'Python'}

Example 3: In this example, let us demonstrate the copy() method on a mixed set.

#Intializing the Set
c1 = {"python",5,11.25}
# Creating copy of Original set
c2=c1.copy()
# Printing both the Set
print("Set c1 ",c1)
print("Set c2 ",c2)
# Adding data to original Set
c1.add("Hi")
# Adding data to shallow copy of the Set
c2.add("Hello")
#Printing again
print("Set c1 ",c1)
print("Set c2 ",c2)

Output

Set c1 {11.25, 5, 'python'}
Set c2 {11.25, 5, 'python'}
Set c1 {'Hi', 11.25, 5, 'python'}
Set c2 {11.25, 5, 'Hello', 'python'}

Conclusion

The copy() method allocates the separate memory for copied set. Hence, updates in the copied set will not be reflected in the original set whenever updates are done.

References

Happy Learning 🙂