Given below is the code showing use of copy() function.
s = set([1, 2, 3, 4, 5])
t = s.copy()
g = s
print s == t #Output: True
print s == g #Output: True
What is use of copy() function when we can simply assign value of s in g?
Why do we have a separate function('copy') to do this task?
Continue with your example by modifying g: s will change, but t won't.
>>> g.add(4)
>>> g
set([1, 2, 3, 4])
>>> s
set([1, 2, 3, 4])
>>> t
set([1, 2, 3])
Because those two assignments aren't doing the same thing:
>>> t is s
False
>>> g is s
True
t may be equal to s, but .copy() has created a separate object, whereas g is a reference to the same object. Why is this difference relevant? Consider this:
>>> g.add(6)
>>> s
set([1, 2, 3, 4, 5, 6])
>>> t
set([1, 2, 3, 4, 5])
You might find this useful reading.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With