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.
langs = {'Python','C++','Java'}
copiedLangs = langs.copy()
print("Original Set: ", langs)
print("Copied Set: ", copiedLangs)
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.
langs = {'Python','C++','Java'}
copiedLangs = langs.copy()
copiedLangs.add('PHP')
print("Original Set: ", langs)
print("Copied Set: ", copiedLangs)
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.
langs = {'Python','C++','Java'}
copiedLangs = langs # copied using = operator
copiedLangs.add('PHP')
print("Original Set: ",langs)
print("Copied Set: ",copiedLangs)
Original Set: {'Python', 'C++', 'Java', 'PHP'}
Copied Set: {'Python', 'C++', 'Java', 'PHP'}