What is copy in python sets? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

What is copy in python sets?

12th Mar 2019, 10:26 AM
Ashutosh Dash
Ashutosh Dash - avatar
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
12th Mar 2019, 2:06 PM
Solo
Solo - avatar
+ 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
12th Mar 2019, 11:15 AM
Nathan Lewis
Nathan Lewis - avatar
+ 3
You can use it to make a shallow copy of your set: set2 = set1.copy()
12th Mar 2019, 11:17 AM
HonFu
HonFu - avatar
+ 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.
12th Mar 2019, 1:31 PM
Nathan Lewis
Nathan Lewis - avatar
+ 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.
13th Mar 2019, 11:58 AM
Nathan Lewis
Nathan Lewis - avatar
+ 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] ☺
13th Mar 2019, 12:34 PM
Solo
Solo - avatar
0
Vasiliy how does 4 came?
13th Mar 2019, 11:50 AM
Ashutosh Dash
Ashutosh Dash - avatar
- 1
Nathan Lewis As far as I understand, the "copy ()" method is only for lists, dictionaries and sets, and not for variables, right?
12th Mar 2019, 12:59 PM
Solo
Solo - avatar