Python Set copy()

The copy() method returns a shallow copy of the set.

A set can be copied using = operator in Python. For example:

numbers = {1, 2, 3, 4}
new_numbers = numbers

The problem with copying the set in this way is that if you modify the numbers set, the new_numbers set is also modified.

numbers = {1, 2, 3, 4}
new_numbers = numbers

new_numbers.add('5')

print('numbers: ', numbers)
print('new_numbers: ', new_numbers)

When you run the program, the output will be:

numbers:  {1, 2, 3, 4, '5'}
new_numbers:  {1, 2, 3, 4, '5'}

However, if you need the original set unchanged when the new set is modified, you can use copy() method.


The syntax of copy() is:

set.copy()

copy() Parameters

It doesn't take any parameters.


Return Value from copy()

The copy() method modifies the given set. It doesn't return any value.


Example 1: How copy() method works for set?

numbers = {1, 2, 3, 4}
new_numbers = numbers.copy()

new_numbers.add('5')

print('numbers: ', numbers)
print('new_numbers: ', new_numbers)

When you run the program, the output will be:

numbers:  {1, 2, 3, 4}
new_numbers:  {1, 2, 3, 4, '5'}