0

I don't understand why the result of the following code is [1,[2,5]] and not [3,[2,5]]. Why is the element in the sublist changed but the element outside of the sublist isn't?

I'm new to Python so maybe I don't see something which should be very obvious. I've read about deep and shallow copies, but it didn't help.

a = [1,[2,3]]
b = a[:]
a[0] = 3
a[1][1] = 5
print(b)

I created the list slice on line 2. But since it has no start or end values, the slice equals the entire list, right? Then why does 3 change to 5, but 1 stays the same?

Kevin
  • 16,549
  • 8
  • 60
  • 74
Dora
  • 11
  • 2
  • 1
    Possible duplicate of [How to clone or copy a list?](https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list) – Paritosh Singh May 30 '19 at 13:58
  • 1
    It's a *shallow* copy, `a[1]` is still the original (mutable) list. – jonrsharpe May 30 '19 at 13:58
  • 1
    shallow copy makes a new container, but still puts references in the new container/list. Make a deepcopy if you wish to ensure no references remain. – Paritosh Singh May 30 '19 at 13:59
  • Also, [second dupe target](https://stackoverflow.com/questions/17246693/what-exactly-is-the-difference-between-shallow-copy-deepcopy-and-normal-assignm) – Paritosh Singh May 30 '19 at 14:01
  • "I've read about deep and shallow copies, but it didn't help. " -- How so? That is *exactly* the issue here. – John Coleman May 30 '19 at 14:01
  • 2
    I have seen at least one book and several online resources that claim `b = a[:]` is a deep copy - they are wrong. See the standard library `copy.deepcopy()` https://docs.python.org/3.7/library/copy.html – cdarke May 30 '19 at 14:04
  • As Paritosh says. A shallow copy makes a copy of the container, so you could `reverse` the new container and leave the original one untouched, but the references inside both containers still refer to the same objects. A deep copy goes all the way to the bottom making copies of everything. – quamrana May 30 '19 at 14:05
  • @ParitoshSingh Thank you for the links! I read through them and I think I get it now. A shallow copy will make changes to child objects (in this case, that's the sublist `[2,3]`), but it won't affect the parent. – Dora May 31 '19 at 08:25
  • indeed. Simply because the "child objects" are still just references pointing to the same objects. – Paritosh Singh May 31 '19 at 08:29

1 Answers1

0

Because, in Python, each list is an independent object. You can do a deep copy using the module 'copy' to solve this specific problem.

import copy
a = [1,[2,3]]
b = copy.deepcopy(a)
a[0] = 3
a[1][1] = 5
print(b)

Result: [1, [2, 3]]

rfr
  • 16
  • 1