0

I have a matrix that will be filled with objects of the same class, I have done this using 2 for loops.

def main(W,H):
    field=[[None]*W]*H
    for i in range(H):
        for j in range(W):
            field[i][j]=tile()

    # Are the same 
    print(id(field[0][1])) 
    print(id(field[1][1]))
    print(id(field[2][1]))
    print(id(field[3][1]))
    # Are diffret
    print(id(field[0][0])) 
    print(id(field[0][1])) 
    print(id(field[0][2])) 
    print(id(field[0][3])) 

I need all the objects to be different so I can edit and use them separately.

  • even though they have the same ID, filling field[0][0] won't affect the other ones – vale Apr 30 '22 at 11:46
  • @vale thanks for the input but it does affect the others if I change a variable on one all the others in the same colon change as well. – Unoriginal Typo Apr 30 '22 at 12:40
  • Does this answer your question? [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) – Ture Pålsson Apr 30 '22 at 13:43
  • @TurePålsson that is what I tried at first but it didn't work. the hole matrix was changing when I changed one of the elements. Thanks for the input though. – Unoriginal Typo May 01 '22 at 20:00

1 Answers1

0

Try

def main(W,H):
    field=[]
    for i in range(0, H):
      row=[]
      for j in range(0, W):
        row+=[None]
      field+=[list(row.copy())].copy()

    field[0][1]="Test different value" #debug
   
    """
    for i in range(H):
      for j in range(W):
        field[i][j]=tile()
    """

    for i in range (0, H): #debug
      for j in range (0, W):
        print(field[i][j], i, j)

main(3,3)

All items do have the same id, however, changing the value of one of them doesn't affect the others.

I have changed the way field is generated. Probably lists were linked as you didn't used list.copy()

Output:

None 0 0
Test different value 0 1
None 0 2
None 1 0
None 1 1
None 1 2
None 2 0
None 2 1
None 2 2
vale
  • 91
  • 6