1

I wanted to make a copy of a list (literally a separated clone that has nothing sharing with the original). I used copy.copy() and created 2 separated lists, but why does the elements of each copy still seem to share?

It's hard to explain, please check out the following output.

>>> a = [[0,1], [2,3]]
>>> import copy
>>> b = copy.copy(a)
>>> temp = b.pop()
>>> temp
[2, 3]
>>> a
[[0, 1], [2, 3]]
>>> b
[[0, 1]]
>>> temp.append(4)
>>> temp
[2, 3, 4]
>>> a
[[0, 1], [2, 3, 4]]
>>> b
[[0, 1]]

As you see, temp is popped from b, yet when I changed temp (aka append new stuff) then the data in a also changed.

My question is: Is this an expecting behavior of deepcopy? How can I make a totally separate copy of a list then?

P/S: As the above example, I guess I can do
temp = copy.copy(b.pop())
but is this a proper way? Is there any other way to do what I want?

P/S 2: This also happens when I use b = a[:]

Thanks!

chique
  • 113
  • 8
  • 2
    Use `copy.deepcopy` instead. `copy.copy` only makes a shallow copy, i.e. it only copies the one list "layer". See [here](http://stackoverflow.com/q/17873384) and [here](http://stackoverflow.com/q/2612802) for more info. –  Sep 01 '16 at 04:57
  • Thanks, it works! I actually thought copy() was the deepcopy they talked in the documentation. – chique Sep 01 '16 at 05:03

3 Answers3

2

friendly dog commented under the OP and suggested me to use deepcopy(). It works. Thanks!

chique
  • 113
  • 8
2

You should use deepcopy() there because the copy() makes shallow clone of the object that you are referencing not the object inside it.If you want the whole object(with the object inside it) use deepcopy() instead.

Please refer the links for better understanding

What is the difference between a deep copy and a shallow copy?

https://docs.python.org/2/library/copy.html

Community
  • 1
  • 1
Sunil Lulla
  • 797
  • 10
  • 18
1

The copy.copy() was shallow copy. That means, it would create a new object as same as be copied. but the elements within copied object didn't be created, and them also is a reference. -> a = [[0,1], [2,3]] -> import copy -> b = copy.copy(a) # the b be created, but [0,1] [2,3] still are reference -> temp = b.pop() -> temp [2, 3] -> a [[0, 1], [2, 3]] -> b [[0, 1]] -> temp.append(4) -> temp [2, 3, 4] -> a [[0, 1], [2, 3, 4]] -> b [[0, 1]] Docs

agnewee
  • 100
  • 7