sidoshi
sidoshi

Reputation: 2160

List not mutated when passed to a function in some case

I am directly mutating the list here and yet the list is not updated after the function is called. The local list in the function gets updated but it does not change the global list. When I tried with a simpler function, the list does indeed get mutated. Is the bellow code a special case in some way that is causing the list to not be mutated?

def rotate_matrix(matrix):
  width = len(matrix[0])
  height = len(matrix)

  if width != height:
    return matrix

  for layer in range(0, width // 2):
    start = layer
    end = width - layer - 1
      for offset in range(start, end):
        temp = matrix[start][offset]
        matrix[start][offset] = matrix[end - offset][start]
        matrix[end - offset][start] = matrix[end][end - offset]
        matrix[end][end - offset] = matrix[offset][end]
        matrix[offset][end] = temp
  print(matrix) # it is updated here
  return matrix


matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(rotate_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])) # updated
print(matrix) # not updated

Upvotes: 0

Views: 45

Answers (1)

Pankaj Singhal
Pankaj Singhal

Reputation: 16053

You've not passed matrix to the function, and hence it has not changed

Upvotes: 1

Related Questions