1

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?

asked Dec 5, 2016 at 2:48
2
  • 2
    You are appending the same object to the list twice. If you change it it will change at both indexes. Commented Dec 5, 2016 at 2:56
  • append isn't creating the same object in the same memory position, you are explicitely appending the same object. Commented Dec 5, 2016 at 3:00

1 Answer 1

3

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.
answered Dec 5, 2016 at 2:51
3
  • Probably the best way. It might also be worth mentioning the copy module. Commented 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 implemented list.append(Coordinates()) as the way to go. Commented 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. Commented Dec 5, 2016 at 15:03

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.