0
def create_matrix(xy):
    matrix = []
    matrix_y = []
    x = xy[0]
    y = xy[1] 
    for z in range(y):
        matrix_y.append(0)
    for n in range(x):
        matrix.append(matrix_y)
    return matrix

def set_matrix(matrix,xy,set):
    x = xy[0] 
    y = xy[1] 
    matrix[x][y] = set
    return matrix

index = [4,5]
index_2 = [3,4]

z = create_matrix(index)

z = set_matrix(z,index_2, 12)
print(z) 

output:

[[0, 0, 0, 0, 12], [0, 0, 0, 0, 12], [0, 0, 0, 0, 12], [0, 0, 0, 0, 12]]

This code should change only the last array

I'mahdi
  • 23,382
  • 5
  • 22
  • 30
mzama
  • 11
  • 2
  • 1
    Welcome to SO! Please [edit] your "question" to add a bit more details to it. For example, an actual question? What's the problem you're facing? The expected output and the current output? – lepsch Jul 23 '22 at 13:12
  • Maybe it's duplicate of https://stackoverflow.com/questions/6667201/ – Daniel Hao Jul 23 '22 at 20:24
  • Or this one - https://stackoverflow.com/questions/62480060/ – Daniel Hao Jul 23 '22 at 20:28
  • Does this answer your question? [Changing value of a 2D array element changes the complete column](https://stackoverflow.com/questions/62480060/changing-value-of-a-2d-array-element-changes-the-complete-column) – Daniel Hao Jul 23 '22 at 20:29

2 Answers2

1

In your for n in range(x): loop you are appending the same y matrix multiple times. Python under the hood does not copy that array, but uses a pointer. So you have a row of pointers to the same one column.

Move the matrix_y = [] stuff inside the n loop and you get unique y arrays.

Comment: python does not actually have a pointer concept but it does use them. It hides from you when it does a copy data and when it only copies a pointer to that data. That's kind of bad language design, and it tripped you up here. So now you now that pointers exist, and that most of the time when you "assign arrays" you will actually only set a pointer.

Another comment: if you are going to be doing anything serious with matrices, you should really look into numpy. That will be many factors faster if you do numerical computations.

Victor Eijkhout
  • 5,088
  • 2
  • 22
  • 23
0

you don't need first loop in create_matrix, hide them with comment:

#for z in range(y):
#    matrix_y.append(0)

change second one like this, it means an array filled with and length = y:

for n in range(x):
    matrix.append([0] * y)

result (only last cell was changed in matrix):

z = set_matrix(z,index_2, 12)
print(z)

# [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 12]]
Ashgabyte
  • 154
  • 1
  • 5