+ 1
What is copy in python sets?
9 Answers
+ 5
Nathan Lewis
At the beginning I thought that you were mistaken in mentioning a variable, but now I realized that when assigning a variable a "list" object, the variable is converted to an object, as in my example. âș
set1=[1,2,3]
set2=set1
set2[2]=4
set1 == set2
"""""""""""""""""
set1=[1,2,3]
set2=set1.copy()
set2[2]=4
set1 != set2
+ 3
copy is used to duplicate data into new variables, more so memory allocation, rather than pointing to the original data so you may freely edit the copied data without worry of changing the original
+ 3
You can use it to make a shallow copy of your set:
set2 = set1.copy()
+ 2
Vasiliy let me rephrase: Your list, dictionary or set, or variable containing such. OP asked about sets, I assumed we knew what I was referring to, my fault.
+ 2
Vasiliy is showing you the properties of .copy() versus =. Changing a vaule in either set after setting them equal to each other will alter the values in both sets, where as if you copy the set data, they will act as their own objects and changing one value will not affect the copied set.
+ 2
Ashutosh Dash
4 - is an arbitrary number assigned to "set2" with the index "[2]", as a result set2 = [1,2,4], a since set2 = set1, then set1 = set2, which means set1 = [1,2,4] âș
0
Vasiliy how does 4 came?
- 1
Nathan Lewis
As far as I understand, the "copy ()" method is only for lists, dictionaries and sets, and not for variables, right?