Possible Duplicate:
Python: Why is (“hello” is “hello”)?
['hello'] is ['hello'] # gives False
Why? Their ids are different. Why didn't a tuple or a number end up returning False?
Possible Duplicate:
Python: Why is (“hello” is “hello”)?
['hello'] is ['hello'] # gives False
Why? Their ids are different. Why didn't a tuple or a number end up returning False?
Consider the following (Python 2.7.3, 64bit):
>>> a = "Hello"
>>> b = "Hello"
>>> a is b
True
Python interns the short string 'Hello'
, storing it only once. This is an implementation detail and is not guaranteed by the language standard. It may fail on longer strings:
>>> a = "this is a long string"
>>> b = "this is a long string"
>>> a is b
False
Now consider this:
>>> a = ["Hello"]
>>> b = ["Hello"]
>>> a is b
False
a
and b
are two different objects. You can check this with id()
:
>>> id(a)
33826696L
>>> id(b)
33826952L
This is a Good ThingTM because when you do
>>> a[0] = "Goodbye"
>>> a
['Goodbye']
>>> b
['Hello']
However, if you do
>>> a = ["Hello"]
>>> b = a
>>> a is b
True
>>> a[0] = "Goodbye"
>>> b
['Goodbye']
because a
and b
are names that refer to the same object (id(a) == id(b)
). Finally, to show that even though you get
>>> a = ["Hello"]
>>> b = ["Hello"]
>>> a is b
False
the strings are still interned and stored only once:
>>> id(a[0])
33846096L
>>> id(b[0])
33846096L
The is
operator tests to see whether two object references refer to the same object (it is not an equality operator, but an identity operator). In your example you have created two separate lists, therefore you have two different objects, which is why you see False
being returned.
When you create a list using the []
syntax, a new list object is created. Lists are mutable objects and thus, even if two lists happen to contain the same elements, they are not the same objects. You can observe that changing a list by calling one of its modifying methods does in fact not change the ID:
In [1]: a = ["hello"]
In [2]: b = ["hello"]
In [3]: id(a)
Out[3]: 4477468112
In [4]: id(b)
Out[4]: 4477467824
In [5]: a.append("world")
In [6]: id(a)
Out[6]: 4477468112