Joe
Joe

Reputation: 234

Python list assignation

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?

Upvotes: 1

Views: 115

Answers (1)

FMc
FMc

Reputation: 42411

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.

Upvotes: 3

Related Questions