Search code examples
pythonreference

References working differently than expected


I wrote some code to help me see references in action when using the * to "multiply" lists.
The program follows:

empty_row = [None] * len(A[0])
empty_matrix = [ empty_row ] * len(A)

for i in range(len(empty_matrix)):
    print(id(empty_matrix[i]))
    for j in range(len(empty_matrix[0])):
        print("     "+ str(id(empty_matrix[i][j])), end = ", ")
    print()

The output seemed to confirm my assumption that all elements of the matrix reference the same object:

2856577670848
     140733388238040,      140733388238040, 
2856577670848
     140733388238040,      140733388238040, 
2856577670848
     140733388238040,      140733388238040, 

I assign values to each element of the matrix and print the matrix

for i in range(len(A)):
    for j in range(len(A[0])):
        empty_matrix[i][j] = i*10+j

for r in empty_matrix:
    for c in r:
        print(c, end = ", ")
    print()

The output is

20, 21, 
20, 21,
20, 21

It seems that the row is referenced but not its elements.
I expected also the elements of the row to be a reference, ie. I expected to get this output:

21, 21, 
21, 21,
21, 21

Can someone explain to me how/why my expectation is wrong? Where is referencing happening and where not in this code? Or is my code to verify it incorrect?


Solution

  • @Tim Roberts answered the question in his first comment
    "...You are modifying the list by assigning a new integer object to that slot. ..."
    (thank you!)

    I include here the print of the IDs after the assignments, I should have checked this before posting the question, hopefully the question will be useful to some other beginner

    1782995372160
         1782914902928,      1782914902960,
    1782995372160
         1782914902928,      1782914902960,
    1782995372160
         1782914902928,      1782914902960,