0

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?

2
  • 4
    Python has neither call by value nor call by reference semantics. It uses a single evaluation strategy, call by object sharing. Note, you are almost certainly talking about list objects and not either of the typical array objects in python. In any case, it sounds like what you need is to simply copy or perhaps deep copy your lists at some point, but you need to provide an actual minimal reproducible example of the problems you are encountering, this is a classic example of the X-Y problem. Commented Dec 8, 2019 at 7:56
  • in Python we often create new list when we modify old list - so it doesn't need to pass by value or clone it.
    – furas
    Commented Dec 8, 2019 at 8:06

1 Answer 1

0

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).

2
  • thank you. This was exactly what I was looking for. For anyone looking for the answer this was my solution: listA = copy.deepcopy(listB) makes a copy of the data in listB and populates in a new collection thus making it act like pass-by-value.
    – AayushD D
    Commented Dec 9, 2019 at 1:05
  • @AayushDD I'm glad that it worked for you, your up vote and also chose my answer as the best answer (from the sidebar which is placed on the left side of my answer), encourage me for more answers. Thank you.
    – Arashsyh
    Commented Dec 9, 2019 at 7:38

Not the answer you're looking for? Browse other questions tagged or ask your own question.