0

I got familiar of the fact that lists and numpy arrays have a strange behavior and there are a couple of posts that say why but they don't say anything about how to workaround the problem.

So, Python behaves like this:

`a = [1,2,3]`
`a`
`[1,2,3]`
`b=a`
`b=[1,2,3]`
`b`
`[1,2,3]`
`b[1] = 84`
`a`
`[1,84,3]`

What is the best workaround to achieve the following behavior?

`a = [1,2,3]`
`b=a`
`b[1] = 84`
`a`
`[1,2,3]`
  • **All** Python objects behave this way. This is not some strange detail of `list`s or `numpy.array`. If you want a copy, you have to explicitly make a copy. Whenever you do `a = b` then *a **is** b* – juanpa.arrivillaga Sep 04 '17 at 21:41
  • `b = a[:]`? Hard to say. Seems you want to modify `b` and leave `a` unchanged? – roganjosh Sep 04 '17 at 21:42
  • 1
    Also note, both `list`s and `numpy.ndarray`s have a convenient `.copy()` method. And also, it is very important to understand, **all python objects** behave this way, it is simply the semantics of the assignment statement in Python. Check out Ned Batcheder's [Facts and myths about Python names and values](https://nedbatchelder.com/text/names.html) which explains in detail the semantics in Python. – juanpa.arrivillaga Sep 04 '17 at 21:43

1 Answers1

0

You wrote b = a, which takes a reference to the underlying object.

You want to write

b = list(a)

which will perform a shallow copy. Then you can mutate a or b independently of one another. For numpy this corresponds to b = np.array(a). Or use b = a.copy(), whether a is a list or NP array.

J_H
  • 17,926
  • 4
  • 24
  • 44