Skip to main content

copy()

The copy() function in Python is a method used to create a shallow copy of a set. This means that it returns a new set with the same elements as the original set, but does not create copies of the elements themselves. The new set created with copy() method is independent of the original set, so any modifications made to one set will not affect the other.

Parameter Values

This function does not accept any parameters.

Return Values

The copy() method from Set Methods returns a shallow copy of the set, which is a new set object.

How to Use copy() in Python

Example 1:

Return a shallow copy of a set.

set_1 = {1, 2, 3}
set_2 = set_1.copy()
print(set_2)  # Output: {1, 2, 3}
Example 2:

Changes made in the original set won't reflect in the copied set.

set_1 = {4, 5, 6}
set_2 = set_1.copy()
set_1.add(7)
print(set_1)  # Output: {4, 5, 6, 7}
print(set_2)  # Output: {4, 5, 6}
Example 3:

Useful when you need to manipulate a set without affecting the original one.

set_1 = {8, 9, 10}
set_2 = set_1.copy()
set_2.remove(10)
print(set_1)  # Output: {8, 9, 10}
print(set_2)  # Output: {8, 9}