Python Set copy() Method

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

Syntax:

set.copy()

Parameters:

No parameters.

Return Value:

Returns a shallow copy of the original set.

The following example demonstrates the set.copy() method.

Example: Copy Set
langs = {'Python','C++','Java'}
copiedLangs = langs.copy()
print("Original Set: ", langs)
print("Copied Set: ", copiedLangs)
Output
Original Set:  {'Python', 'C++', 'Java'}
Copied Set:  {'Python', 'C++', 'Java'}

Any update in the copied set does not affect the original set, as shown below.

Example: copy()
langs = {'Python','C++','Java'}

copiedLangs = langs.copy()
copiedLangs.add('PHP')

print("Original Set: ", langs)
print("Copied Set: ", copiedLangs)
Output
Original Set:  {'Python', 'C++', 'Java'}
Copied Set:  {'Python', 'C++', 'Java', 'PHP'}

We can also copy the set using an = operator, but when any change is made to the copied set, it will also be reflected in the original set, as shown below.

Example: Copy using = Operator
langs = {'Python','C++','Java'}

copiedLangs = langs  # copied using = operator
copiedLangs.add('PHP')

print("Original Set: ",langs)
print("Copied Set: ",copiedLangs)
Output
Original Set:  {'Python', 'C++', 'Java', 'PHP'}
Copied Set:  {'Python', 'C++', 'Java', 'PHP'}
Want to check how much you know Python?