0

For example, if I had a list

t = [["a","b","c"],["d","e","f"],["g","h","i"]]

and I copied it and changed element [1][1] to "z" like this

t2 = t.copy()
t2[1][1] = "z"

when I print both tables, only t2 should be changed but the original table is affected as well, why is this? I'm not sure if this questions has been asked before so I apologize if this is a repeated question but I've been having trouble understanding this. Thanks.

3 Answers3

1

copy performs a shallow copy - i.e., you get a new "outer" list that points to the same "inner" lists the original points to. If this is not the desired behavior, you could use deepcopy instead:

>>> from copy import deepcopy
>>> t = [["a","b","c"],["d","e","f"],["g","h","i"]]
>>> t2 = deepcopy(t)
>>> t2[1][1] = "z"
>>> t
[['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]
>>> t2
[['a', 'b', 'c'], ['d', 'z', 'f'], ['g', 'h', 'i']]
Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

In python, copy() does a shallow copy, see https://docs.python.org/2/library/copy.html

A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.

So in your example, t2[1]=["j","j","j"] will not affect t, but if you want to go to the next level, you need to to a deep copy

supamanda
  • 199
  • 2
  • 3
0

You need to do a deep copy. Try this:

import copy
t = [["a","b","c"],["d","e","f"],["g","h","i"]]
t2 = copy.deepcopy(t)
t2[1][1] = "z"

Now t should have its original constents, while the copy in t2 got affected by the change requested

Jorge Torres
  • 1,426
  • 12
  • 21