I can’t find concise information about what is going on in this very simple program:
print 'case 1'
# a and b stay different
a = [1,2,3]
b = a
b = [4,5,6]
print 'a =',a
print 'b =',b
print
print 'case 2'
# a and b becomes equal
a = [1,2,3]
b = a
b[0] = 4
b[1] = 5
b[2] = 6
print 'a =',a
print 'b =',b
print
print 'case 3'
# a and b stay different now
a = [1,2,3]
b = a[:]
b[0] = 4
b[1] = 5
b[2] = 6
print 'a =',a
print 'b =',b
print
print 'case 4'
# now the funny thing
a=[1,2,[3]]
b=a[:]
b[0] = 4
b[1] = 5
b[2][0] = 6 # this modifies b and a!!!
The output of this simple test is:
case 1
a = [1, 2, 3]
b = [4, 5, 6]
case 2
a = [4, 5, 6]
b = [4, 5, 6]
case 3
a = [1, 2, 3]
b = [4, 5, 6]
case 4
a = [1, 2, [6]]
b = [4, 5, [6]]
I clearly do not understand how python handles each case. Could any one provide a link so that I can read about it, or a short explanation of what is happening?
Thanks a lot.
This is a fantastic visualization tool for python code.
Run your code in it and everything should become clear in a minute.