Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading