Explanation of list reference

Chris Angelico rosuav at gmail.com
Sat Feb 15 12:21:29 CET 2014


On Sat, Feb 15, 2014 at 8:44 PM, Christian Gollwitzer <auriocus at gmx.de> wrote:
>>>> import numpy as np
>>>> a=np.array([1, 2, 3, 4])
>>>> b=a[:]
>>>> id(a)
> 140267900969344
>>>> id(b)
> 140267901045920
>
> So, a and b are different things, right?
>
>>>> b[1]=37
>>>> b
> array([ 1, 37,  3,  4])
>>>> a
> array([ 1, 37,  3,  4])
>
> Still they are connected.

Well, yes, they are different things; but that doesn't mean they can't
affect each other. And you don't need numpy to see that:

>>> d = {}
>>> k1 = d.keys()
>>> k2 = d.keys()
>>> k1 is k2
False
>>> k1 == k2
True
>>> d[1]=1
>>> k1
dict_keys([1])
>>> k2
dict_keys([1])

Two separate keys views on the same dictionary will, by definition,
always show the same keys (and, I think, in the same order). But
they're still separate objects. Their identities are distinct, their
values are linked.

ChrisA



More information about the Python-list mailing list