Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Python references

Tags:

python

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?

like image 316
Nikhil J Joshi Avatar asked Apr 23 '26 08:04

Nikhil J Joshi


1 Answers

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']]
like image 166
NPE Avatar answered Apr 24 '26 23:04

NPE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!