How to pass a matrix as an argument without changing its original values in Python

Question:

I am trying to pass a matrix (list of lists) as an argument to a function. I want to keep the original matrix values intact. How can I implement this in python? I have tried to copy the matrix in a new variable temp, but it is still not working.

ideal = [[5,1,2,3,4],[6,7,8,9,10],[11,12,13,14,15],[16,17,18,19,20],[21,22,23,24,25]]
print(ideal)
for i in range(1):
    temp = ideal
    print(rotate_col_down(temp,i))
print(ideal)

output:

[[5, 1, 2, 3, 4], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 23, 23, 24, 25]] #ideal
[[21, 1, 2, 3, 4], [5, 7, 8, 9, 10], [6, 12, 13, 14, 15], [11, 17, 18, 19, 20], [16, 23, 23, 24, 25]]
[[21, 1, 2, 3, 4], [5, 7, 8, 9, 10], [6, 12, 13, 14, 15], [11, 17, 18, 19, 20], [16, 23, 23, 24, 25]] # changed ideal

Here is the function that i am trying to implement

def rotate_col_down(state, j):
    temp = state[ROWS-1][j]
    for i in range(ROWS-1,0,-1):
        state[i][j]= state[i-1][j]
    state[0][j] = temp
    return(state)
Asked By: Saurabh Damle

||

Answers:

You ran into the fact that python is mostly pass-by-reference instead of value (compare this post with answers).

You can solve this in your code by using .copy() or copy.deepcopy() (compare how-to-deep-copy-a-list)

So a solution would be

import copy

ideal = [[5,1,2,3,4],[6,7,8,9,10],[11,12,13,14,15],[16,17,18,19,20],[21,22,23,24,25]]

print(ideal)
for i in range(1):
    print(rotate_col_down(copy.deepcopy(ideal),i))
print(ideal)
Answered By: LinFelix
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.