Given that everything in python is by reference, I do understand what's happening in the code below:
a = ['one']*3 // a = ['one', 'one', 'one']
b = [a]*3 // b = [['one', 'one', 'one'], ['one', 'one', 'one'], ['one', 'one', 'one']]
b[1][2] = 'two'
And now, b is
[['one', 'one', 'two'], ['one', 'one', 'two'], ['one', 'one', 'two']]
Because we made b refer three times the same object referred by a, reassigning any one of the component, change is seen at three places.
But, then why the same thing occurs when
a = [['one']]*3 // a = [['one'], ['one'], ['one']]
a[1] = ['two']
does not make a = ['two', 'two', 'two'], but just [['one'], ['two'], ['one'] as if a now has three different objects pointed to.
Am I missing some logic here?
You are not changing the contents of a[1], you are rebinding it to point to a separate array. This has no effect on a[0] and a[2].
Try the following instead:
In [4]: a = [['one']]*3
In [5]: a[1][0] = 'two'
In [6]: a
Out[6]: [['two'], ['two'], ['two']]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With