2
a = [10, 23, 56, [78]]
b = list(a)
a[3][0] = 95
a[1] = 34
print(b)

Output: [10, 23, 56, [95]]

Is there any particular reason why the nested value gets changed from 78 to 95; however, the value at the index value = 1 remains 23 only?

Edit explaining my question better:

I've received comments explaining that when I do new_list = old_list, changes made in any list will be seen in both the variables. But what I don't understand in this particular case is that why is only one value changing i.e. 95, but not the other value i.e. 23.

  • 1
    Not an exact duplicate, but does this answer your question? [List changes unexpectedly after assignment. How do I clone or copy it to prevent this?](https://stackoverflow.com/questions/2612802/list-changes-unexpectedly-after-assignment-how-do-i-clone-or-copy-it-to-prevent) – Pranav Hosangadi Nov 02 '20 at 05:47
  • 3
    I think when you use `b=list(a)`, `list` copies all elements to `a`, but the last item is list too, so `list` copies the item by link (ref). – Musulmon Nov 02 '20 at 05:47
  • 3
    You made a shallow copy when it sounds like you wanted a deep copy. – user2357112 Nov 02 '20 at 05:48
  • 2
    Does this answer your question? [Copying nested lists in Python](https://stackoverflow.com/questions/2541865/copying-nested-lists-in-python) – StardustGogeta Jul 13 '21 at 15:52

0 Answers0