Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use Inbuilt copy() function for sets in python when we can simply assign it? [duplicate]

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?

like image 945
DOSHI Avatar asked Jan 28 '26 05:01

DOSHI


2 Answers

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])
like image 166
user2839978 Avatar answered Jan 29 '26 17:01

user2839978


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.

like image 41
jonrsharpe Avatar answered Jan 29 '26 19:01

jonrsharpe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!