0

I wanted to create a 2D array that would have a number in each cell. I need to access specific cells and be ablt to change them.

def print_matrix(matrix):
    #just to print it nicer
    for x in range(0, len(matrix)):
        print(matrix[x])

matrix = []
list = []
for x in range(0,10):
    list.append(0)

for x in range(0,10):
    matrix.append(list)

matrix[1][2] = 9


print_matrix(matrix)

3 Answers3

1

You actually created only one list and added it 10 times to the matrix (by reference).

matrix = []
for x in range(0,10):
    row = []

    for x in range(0,10):
        row.append(0)

    matrix.append(row)

Also, it's not advisable to call variables list, for this is a builtin python function.

Itay
  • 16,601
  • 2
  • 51
  • 72
1

Use list.copy():

def print_matrix(matrix):
    #just to print it nicer
    for x in range(0, len(matrix)):
        print(matrix[x])

matrix = []
list = []
for x in range(0,10):
    list.append(0)

for x in range(0,10):
    matrix.append(list.copy())

matrix[1][2] = 9


print_matrix(matrix)

If you don't use copy, matrix simply holds 10 references to the original list. Changing any one of those references simply changes the original list.

When you use .copy(), new lists are created which are copies of the original one, this allows you to change each one independently.

Omer Tuchfeld
  • 2,886
  • 1
  • 17
  • 24
0

Your problem is that you have list references in each row in your matrix. Check here for a possible solution.

hajduzs
  • 83
  • 1
  • 7