Changing one of two objects that are the same in memory does not change the other object

Viewed 35

Simply, I have two lists that are the same object, as

lines.append(l1)
lines[-1] is l1
>>True

This evaluates to True, so they should be the same point in memory. But when I make

l1=[]
lines[-1]==l1
>>False

I don't understand how two objects could point to the same point in memory, as lines[-1] is l1 evaluates to true but then changing l1 does not change lines[-1]. The actual code I was using that caused this is

number=['0,9 -> 5,9', '8,0 -> 0,8', '9,4 -> 3,4', '2,2 -> 2,1', '7,0 -> 7,4', '6,4 -> 2,0', '0,9 -> 2,9', '3,4 -> 1,4', '0,0 -> 8,8', '5,5 -> 8,2']
lines=[]
for i in number:
    i=i.split("->")
    i[0]=i[0][:-1]
    i[1]=i[1][1:]
    
    s1 = i[0].split(",")
    s2 = i[1].split(",")
    l1 =[s1,s2]
    lines.append(l1) 
    print(l1==lines[-1],l1 is lines[-1]) #evalutes to True True
    l1=[]
    print(l1==lines[-1],l1 is lines[-1]) #evalutes to False False
    print(l1,lines[-1],"\n")

Like how could l1 be lines[-1], but changing l1 does not change lines[-1]?

I think the problem lies with assigning l1 to a new value. If I just did l1.append(1), then the code works as expected. However, doing l1 = [32,32] or some other arbitrary assignment then the code does not work as expected.

1 Answers

The reason the append method works is because it is an inplace operator. While an assignment just changes the memory address without changing the values at the previous memory address.

Related