Search code examples
pythonarraysmultiplication

How does python references work in a list


I was reading this post How to Initialize a 2d Array

I understand that the issue here is that a list is referencing the same list. So if you edit one of the elements. All the references will reflect this change.

But in a case such as:

x = 1
y  = [x]*5
# y = [1, 1, 1, 1, 1]
x = 2
# why doesn't y = [2, 2, 2, 2, 2]??

Shouldn't y change because each element is referencing x?


Solution

  • You misunderstood. There are 5 distinct references. If those 5 references all point to the same nested list and you alter that nested list, you can see the change reflected through all those references.

    You didn't change a nested list here. You changed one of the references.

    Think of references as nametags. You can put more than one nametag on an object:

    nametag_a+-----------+
                     +---v--+
                     |object|
                     +---^--+
                         |
    nametag_b+-----------+
    

    You can 'look' at the object through either reference. Assignment is simply attaching a reference to an object. If a reference pointed to an object before, it is detached from that object and now points to another object:

    nametab_b = another_object
    

    results in

    nametag_a+-----------+
                     +---v--+
                     |object|
                     +------+
    
    nametag_b    +--------------+
        +-------->another_object|
                 +--------------+
    

    The numbered indices in a list are references to; so instead of nametag_a, you have 0, and 1, etc.

    The other question talks about nested lists. There you have multiple references to a single list object:

    # indices in a list on the left referencing another list
    
    0+---------------------------+
                                 |
                                 |
    1+------------------------+  |
                              |  |
                    +---------v--v-----------+
    2+--------------> list with more indices |
                    +---------^--^-----------+
                              |  |
    3+------------------------+  |
                                 |
                                 |
    4+---------------------------+
    

    If you make a change to the list with more indices contents, then you'll see those changes through any of the 5 references in the outer list

    Please read Facts and myths about Python names and values by Ned Batchelder, which explains this in more detail.