Does python pass by reference, value, or object? It is quite confusing even after reading some posts. I still don't understand how I got the weird result. Could anyone help explain how the weird result came into being and how to achieve the correct result?
I tried to rotate a 2D list in python. when no function is invoked as shown in case 1, I get the correct result. However, when I put the code in a function, it returns a weird result, which is not what I expected. Why is the output in case 2 [[9, 6, 3], [8, 5, 2], [7, 4, 1]]? Where did it come from?
case 1:
matrix = [[1,2,3],[4,5,6],[7,8,9]]
matrix = matrix[::-1]
for i in range(len(matrix)):
for j in range (len(matrix[0])):
if i<=j:
matrix[j][i],matrix[i][j] =matrix[i][j], matrix[j][i]
print(matrix)
case 2:
def rotate(matrix) -> None:
print('1',matrix)
matrix = matrix[::-1]
print('2',matrix)
for i in range(len(matrix)):
for j in range (len(matrix[0])):
if i<=j:
matrix[j][i],matrix[i][j] =matrix[i][j], matrix[j][i]
print('3',matrix)
matrix = [[1,2,3],[4,5,6],[7,8,9]]
rotate(matrix)
print(matrix)
case 1 output:
[[7, 4, 1], [8, 5, 2], [9, 6, 3]]
case 2 output:
1 [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
2 [[7, 8, 9], [4, 5, 6], [1, 2, 3]]
3 [[7, 4, 1], [8, 5, 2], [9, 6, 3]]
[[9, 6, 3], [8, 5, 2], [7, 4, 1]]