-1

I have the following code in Python 3:

def matrix(n:int) -> list:
    matrix = list([[None]*n]*n)

    count = 1
    for i in range(n):
        for j in range(n):
            print(i, j, count)
            matrix[i][j] = count
            count += 1

    return matrix

number = 3
print(matrix(number))

Below is the print result:

    0 0 1
    0 1 2
    0 2 3
    1 0 4
    1 1 5
    1 2 6
    2 0 7
    2 1 8
    2 2 9
    [[7, 8, 9], [7, 8, 9], [7, 8, 9]]

As you see, indexes are correct, but it does not return the expected value of [[1, 2, 3], [4, 5, 6], [7, 8, 9]]. There has to be a fundamental reason for this behavior, and of course, by using other methods, such as append(), the result is correct.

Sami
  • 1,473
  • 1
  • 17
  • 37

1 Answers1

1

matrix = list([[None]*n]*n) can makes some problems, you can read more about it in here

I would do it as:

def matrix(n:int) -> list:
     matrix = []
     count = 1
     for i in range(n):
         matrix.append([])
         for j in range(n):
             matrix[i].append(count)
             count+=1

     return matrix

number = 3
print(matrix(number))

to avoid problems with mutable objects

Update

If you want a oneliner:

def g(n):
     return [list(range(i+i+1, i+n+i+1)) for i in range(0,n*2, 2)]
Reznik
  • 2,663
  • 1
  • 11
  • 31