2

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?

DOSHI
  • 442
  • 2
  • 23

4 Answers4

4

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])
user2839978
  • 341
  • 2
  • 6
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.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
2

From the docs:

Assignment statements in Python do not copy objects, they create bindings between a target and an object.

You can visualize the difference here. Notice s and g point to the same object, where as t points to a shallow copy of the two.

Dair
  • 15,910
  • 9
  • 62
  • 107
2

Sets are mutable objects in Python, so depending on what you are doing with it, you may want to operate over a copy instead in order to prevent the propagation of any changes you make.

If you are sure the operations you are performing have no side effects, go ahead and just assign it. In this case, be aware that any change to the value pointed by s will also affect the value of t, because both point to the same set instance (it helps if you think of python variables as C pointers).

Paulo Scardine
  • 73,447
  • 11
  • 124
  • 153