-1

I need to create a function that transpose a matrix (to basically transform rows into columns, and columns into rows) by modifying directly the reference of the list (the function should not return any value, or print anything, it should be modified directly through the reference :

The following matrix :

1 2 3
4 5 6
7 8 9

should be transformed into

1 4 7
2 5 8
3 6 9

However, my code is not accepted :

def transpose(matrix):
    matrix = [[matrix[j][i] for j in range(len(matrix))] for i in range(len(matrix[0]))]

I can't understand why... Is this code modifying only the value of the list, and not the reference ?

Any suggestion ? (I need to use "for ... " function from python).

Thank you in advance !

  • You are assigning a new value to the local variable `matrix`, at which point it no longer refers to the original list at all. Assigning to `matrix[:]` instead would replace the old contents, while leaving the variable as a reference to the list. – jasonharper Apr 11 '22 at 18:15
  • you are assigning a new copy – d_kennetz Apr 11 '22 at 18:15
  • Your code attempts to assign a new value to `matrix`. That tells you you're modifying the parameter itself, not just what it contains. – Mark Reed Apr 11 '22 at 18:15

1 Answers1

0

You bind the name matrix to a new variable, so it's not call by reference. You could use your code and directly assign to the slice like so:

def transpose(matrix):
    matrix[:] = [[matrix[j][i] for j in range(len(matrix))] for i in range(len(matrix[0]))]

Alternatively, if you want to explicitly use for, you could use this snippet:

from copy import copy

def transpose(matrix):
    temp = copy(matrix)
    for i in range(len(matrix)):
        for j in range(len(matrix[i])):
            matrix[i][j] = temp[j][i]
rammelmueller
  • 1,092
  • 1
  • 14
  • 29