1

Why shallow copy working in different for nested list elements and non nested list elements? I don't understand why it is doing like this.

It is doing shallow copy function is working in two different ways:

  1. for non-nested list elements working as deep copy
  2. for nested list elements working as shallow copy.

here I am providing the code for that. please give me clarity on this. with graphics possibly.

lst_1 = [1,2,[3,4],5]

lst_2 = lst_1.copy()

lst_1[2][0] = 'Now'

lst_2[0]='haha'

print(lst_1)

print(lst_2)

output is:

[1, 2, ['Now', 4], 5]

['haha', 2, ['Now', 4], 5]
Raymond Chen
  • 44,448
  • 11
  • 96
  • 135
  • "A [shallow copy](https://docs.python.org/2/library/copy.html) constructs a new compound object and then (to the extent possible) inserts **references** into it to the objects found in the original." Therefore, `lst_2`'s elements are references to the same `1`, `2`, `[3,4]`, and `5` as `lst_1`. So `lst_1[2]` is the same reference as `lst_2[2]`. – Raymond Chen Feb 03 '22 at 04:47
  • 'lst_1 = [1,2,[3,4],5]\ lst_2 = lst_1.copy()\ lst_2[2][0] = 'Now'\ lst_2[0]='haha'\ print(lst_1)\ print(lst_2)'\ **changes in lst_2[2][0] affecting list_1[2][0] but change in list_2[0] not affecting in list_1[0]. If the references are copied then why not changing in list_1. – cherukupally kalyan Feb 05 '22 at 14:08
  • After the copy, `list_2[0]` and `list_1[0]` are both references to the number 1. After `list2_[0] = 'haha'`, `list_2[0]` is now a reference to `'haha'`. This has no effect on `list_1[0]`. `list_1[0]` is still a reference to the number 1. – Raymond Chen Feb 05 '22 at 14:59

0 Answers0