Gotcha Question
Akira Kiyomiya
akira.kiyomiya at autodesk.com
Wed Mar 8 14:46:07 EST 2000
Well, there was a gotcha question from Learning Python form O'Reilly at p64
and it is really a gotcha question since it got me....
Could someone explain why it is in dummy's language? Maybe I am not used
to Python stuff.
1.
>>> L = [1, 2, 3]
>>> M = ['X', 'L', 'Y'] #embed a reference to L
>>> M
['X', [1, 2, 3], 'Y']
>>> L[1] = 0 #changes M too
>>> M
['X', [1, 0, 3], 'Y'] #yeah, I can understand it. Easy.
>>> L = [1, 2, 3]
>>> M = ['X', L[:], 'Y'] #embed a copy of L
>>> L[1] = 0 #only changes L, not M
>>> L
[1, 0, 3]
>>>M
['X', [1, 2, 3], 'Y'] #Why?? I know it only changed L, not M. But
why is it?
2.
>>>L = [4, 5, 6]
>>> X = L * 4
>>>Y = [L] * 4
>>> X
[4, 5, 6, 4, 5, 6, 4, 5, 6, 4, 5, 6] # yeah, it is easy
>>>Y
[[4, 5, 6], [4, 5, 6], [4, 5, 6], [4, 5, 6]] # yeah, it is easy
>>> L[1] = 0; # impacts y but not x
>>> X
[4, 5, 6, 4, 5, 6, 4, 5, 6, 4, 5, 6] # why?
>>>Y
[[4, 0, 6], [4, 0, 6], [4, 0, 6], [4, 0, 6]] # yeah, I understand this.
More information about the Python-list
mailing list