I've got this code
class coordenates:
x = 0
y = 0
coor = coordenates()
coor.x=0
coor.y=0
list = []
list.append(coor)
list.append(coor)
Now, the problem is that when I update
list[0].x=100
it is also modifing list[1].x
somehow!
print str(list[0].x)
>> 100
print str(list[1].x)
>> 100
which must remain in 0
since I haven't update it. Is append()
creating the same object pointing in the same position in memory in positions 0 and 1? why creating 2 different objects solves the problem?
1 Answer 1
In your current code, x
and y
are class-level attributes. I suspect that you want them to be instance-level attributes. If so, set them in __init__()
:
class Coordinates:
def __init__(self):
self.x = 0
self.y = 0
More important, if you append the same coor
to the list twice, any mutation of the coor
will be reflected in "both" coordinates (because the list is just holding a reference to the same underlying coordinate in both positions of the list). Maybe you want something like this instead, where you create two independent coordinate instances?
list = []
list.append(Coordinates())
list.append(Coordinates())
You can see an illustration of your problem with this code:
c = Coordinates()
cs = []
cs.append(c)
cs.append(c)
for c in cs:
print id(c) # Both elements of the list refer to the same object.
-
Probably the best way. It might also be worth mentioning the
copy
module.pbreach– pbreach12/05/2016 03:08:27Commented Dec 5, 2016 at 3:08 -
So if I do
temp= 0, list.append(temp), list.append(temp)
list[0]=100 will modify both positions as well? btw amazing response! I implementedlist.append(Coordinates())
as the way to go.Joe– Joe12/05/2016 08:47:21Commented Dec 5, 2016 at 8:47 -
@Joe Well ... that example is a bit different. You are assigning an entirely new object (an integer
100
) to the[0]
element. In the initial example, we were appending the same object (coor
) to the list twice, and then mutating the underlying object.FMc– FMc12/05/2016 15:03:09Commented Dec 5, 2016 at 15:03
append
isn't creating the same object in the same memory position, you are explicitely appending the same object.