0

I have run following code. I expected that elements of list c will not refer to a, but be a copy os list a, but the result contradicts. Why?

>>> a = [[]]
>>> b = a *3
>>> c = a[:] *3    // should create a copy of a three times
>>> b[1].append(6)
>>> b
[[6], [6], [6]]
>>> c
[[6], [6], [6]]    // but it is referring to a 
  • 4
    Because the copying is a *shallow* copy. The nested list will not be copied. – Some programmer dude Dec 15 '20 at 04:56
  • 1
    Line number 2 actually copies reference of `a` three times. So, basically you have `b = [ref(z), ref(z), ref(z)]`, where `z` represents the item inside list `a`. When you update one, that is reflected in other two lists. You can do following: `>>> b = [[] for i in range(3)]` – Dileep Dec 15 '20 at 04:59
  • 1
    What you want is a _deep copy_ see [`copy.deepcopy`](https://docs.python.org/3/library/copy.html#copy.deepcopy) – ssp Dec 15 '20 at 05:04
  • Never use the `*` operator on lists unless you are dealing with a single dimension of primitives or you want aliasing of the objects within the list. Tossing `[:]` on before `*` does nothing but waste memory. – ggorlen Dec 15 '20 at 05:15

0 Answers0