[Python] Python list referencing itself - how does it work?

Discussão em 'Python' iniciado por Stack, Abril 8, 2025.

  1. Stack

    Stack Membro Participativo

    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?

    Continue reading...

Compartilhe esta Página