I am newbie to python so having difficulty understand this code behavior for scenarios listed below.
I can understand the first 3 where the output is a=[1], b=[0] but in the last case why is the value of b getting changed to [1] ?
a = [0]
b = a[:]
a = [1]
print(a,b)
a = [0]
b = a[:]
a[0] = 1
print(a,b)
a = [0]
b = a
a = [1]
print(a,b)
a = [0]
b = a
a[0] = 1
print(a,b)
Here are some comments that should help clarify.
You should check out this python visualizer to help clarify things, since it will show you exactly what object each reference is pointing to. Paste your code in there, then click
Visualize Executionand step through the code to visualize the differences between these 4 blocks.Specifically in this case, pay close attention to what happens on the
b = alines. Both variables will point to the same underlying list.