0

This is the python code I was trying out

a=[100,203,56,[18]]
b=list(a)
a[3][0]=89
a[1]=23
print(b)

and I got the following output:

[100, 203, 56, [89]]

I am not understanding why only one assignment worked and not the other and secondly I am printing the variable b , how is me changing 'a' affecting 'b'

Additionally, when I write

b[1]=23

instead of

a[1]=23

the output changes and I get

[100, 23, 56, [89]]

edit: despite few answers giving me the solution, I am not able to understand why only one element in the list changes but not the other

  • 2
    http://pythontutor.com/visualize.html – deceze Sep 30 '21 at 11:53
  • I don't think that's *quite* a dup from the OP's point of view: although *I* can see that the inner list at `a[3]` is referenced in b, that question doesn't quite make that clear. @SrishtiBhat you want to go through what's happening in the other question carefully, and read about how python assigns variables. (In this case, btw, you could get an unchanged `b` by doing `from copy import deepcopy` and then `b = deepcopy(a)` – 2e0byo Sep 30 '21 at 11:57
  • @deceze that's a great resource, I'm going to keep that on hand for next time this kind of q comes up – 2e0byo Sep 30 '21 at 11:58
  • @2e0byo well, I am still not understanding why a[1] =23 does not work but the other assignment does. – Srishti Bhat Sep 30 '21 at 12:14
  • Define "not work". It works just fine. – deceze Sep 30 '21 at 12:28
  • But well, it boils down to `list(a)` making a *shallow* copy. I makes a copy of the outer `[...]`, it doesn't make a copy of each element within it. So `a[3]` and `b[3]` still refer to the same list object. – deceze Sep 30 '21 at 12:32
  • not work - meaning the output does not show changes for a[1]=23 but for a[3][0] = 89 the changes are displayed. – Srishti Bhat Sep 30 '21 at 13:01
  • Ok, so, did you understand the above explanation and all the linked duplicates? – deceze Sep 30 '21 at 13:11
  • Have managed to understand with the help of visualizer :) Thank you so much – Srishti Bhat Sep 30 '21 at 13:48

0 Answers0