-1

I am trying to edit a 5 * 5 square matrix in Python.And I initialize every element in this 5 * 5 matrix with the value 0. I initialize the matrix by using lists using this code:

h = []
for i in range(5):
    h.append([0,0,0,0,0])

And now I want to change the matrix to something like this.

4 5 0 0 0
0 4 5 0 0 
0 0 4 5 0
0 0 0 4 5
5 0 0 0 4

Here is the piece of code -

    i = 0
    a = 0
    while i < 5:
        h[i][a] = 4
        h[i][a+1] = 5
        a += 1
        i += 1 

where h[i][j] is the 2 D matrix. But the output is always is showing something like this -

4 4 4 4 4
4 4 4 4 4
4 4 4 4 4
4 4 4 4 4
4 4 4 4 4

Can you guys tell me what is wrong with it?

Ismael Padilla
  • 5,246
  • 4
  • 23
  • 35

2 Answers2

3

Do the update as follows using the modulo operator %:

for i in range(5):
    h[i][i % 5] = 4
    h[i][(i+1) % 5] = 5

The % 5 in the first line isn't strictly necessary but underlines the general principle for matrices of various dimensions. Or more generally, for random dimensions:

for i, row in enumerate(h):
    n = len(row)
    row[i % n] = 4
    row[(i+1) % n] = 5
user2390182
  • 72,016
  • 6
  • 67
  • 89
0

Question answered here: 2D list has weird behavor when trying to modify a single value

This should work:

#m = [[0]*5]*5  # Don't do this.

m = []
for i in range(5):
    m.append([0]*5)

i = a = 0
while i < 5:
    m[i][a] = 4
    if a < 4:
        m[i][a+1] = 5
    a += 1
    i += 1


leila-m
  • 97
  • 1
  • 9