Search code examples
pythonarrayspass-by-reference

How to pass 2d array in python by value and not by reference?


I have a 2D array that I need to constantly update and assign to different variables but the update has to take place from the initial array. Since lists are passed by reference and not by value the regular assignment does not work. I tried: list1 = list2[:] which works perfectly fine with a 1D arrays but not with a 2D array.

Has anyone encountered this before?


Solution

  • Python Shallow and Deep Copy

    As you said, this kind of assignment is done by reference and not by value. In order to assign mutable data types like lists, numpy arrays and etc. by value, you have to use Python Copy Module. This module provides you with two shallow and deep copy methods that you should chose one of them according to the type of data which you are going to copy. If the object you are going to copy includes another objects like list, classes and ... in itself, you should use deep copy method otherwise, shallow copy should be used (In the above described problem, it seems shallow copy is what you are looking for).