pythonlist

Python list referencing itself - how does it work?


When I use = operator in python, python creates an object for me (if it doesn't exist), and then links my variable to it. So

>>>a = 1
>>>b = a
>>>a = 2
>>>print(f'{a}, {b}') 
2, 1

seem to be ok. For mutable objects, when I change an object, pointers still point to the same object, so this is ok too:

>>>a = []
>>>b = a
>>>a = a.append(1)
>>>print(f'{a}, {b}') 
[1], [1]

Now what if I will do that thing:

>>>a = [1]
>>>a[0] = a
>>>print(f'{a}')

what I was expecting is infinite links so this should provide some error, but python handling it normally, describing a as [[...]]. Now I can access object of any deepness a[0][0][0][0][0] and it still would be [[...]]. Actually [1] should be somewhere in memory, but I'm unable to access it.

Okay, what will happen if I would make this thing now:

>>>a[0][0][0] = 5

I would expect that a becomes either [[[5]]] or it will become 5 by itself (strange but I could say it has some sense). Actually, no. a becomes [5].

Could anyone explain why? How does it work?


Solution

  • When you assign a[0] = a then a is a reference to a list whose first element is a itself. Something like

     a --+--> [ X ]
         ^      |
         |      |
         +------+    
    

    Therefore (a[0])[0][0]=5 simplify to a[0][0]=5 since a[0]=a which in turns simplify to a[0]=5 but not to a = 5.

    Note that there is no infinite list involved here.