tags:

views:

143

answers:

5
+5  A: 

This is because of a Python feature called String interning which is a method of storing only one copy of each distinct string value.

codaddict
+1 for answering the question instead of - out of habit, I guess - saying "don't" :)
delnan
I was looking for this term. Thank you, I will read up. This answer what I am asking.
sukhbir
@unicornaddict: You've answered the last question, but not the first two.
MattH
+10  A: 

This is an implementation detail and absolutely not to be relied upon. is compares identities, not values. Short strings are interned, so they map to the same memory address, but this doesn't mean you should compare them with is. Stick to ==.

Daniel Roseman
Aah I see. I will stick to `==`, however I wanted to be sure what I was doing was correct.
sukhbir
Whether short strings are interned or not is dependent upon the interpreter implementation you're using - you can't ever rely on it.
Nick Bastin
+8  A: 

There are two ways to check for equality in Python: == and is. == will check the value, while is will check the identity. In almost every case, if is is true, then == must be true.

Sometimes, Python (specifically, CPython) will optimize values together so that they have the same identity. This is especially true for short strings. Python realizes that 'Hello' is the same as 'Hello' and since strings are immutable, they become the same through string interning / string pooling.

See a related question: http://stackoverflow.com/questions/1392433/python-why-is-hello-is-hello

carl
Thanks for this.
sukhbir
+1  A: 

In Python both strings and integers are immutable therefore you can cache them. Integers in the range of ´-5´ to ´256´ and small strings(don't know the exact size atm) get cached, therefore they are the same object. x and y are only names that refer to these objects.

Also == compares for equals values, while is compares for object identity. None True and False are global objects, for example you can rebind False to True.

The following shows that not every thing is being cached:

x = 'Test' * 2000
y = 'Test' * 2000

>>> x == y
True
>>> x is y
False

>>> x = 10000000000000
>>> y = 10000000000000
>>> x == y
True
>>> x is y
False
Ivo Wetzel
Thanks for your answer.
sukhbir
+1  A: 

In Python, variables are just names that point to some object (and they can point to the same object). In C++, variables also define the actual memory that is reserved for them; this is why they have distinct memory addresses.

About Python string interning and differences between the two comparison operators, see carl's response.

Messa
Yes I figured it out now. Thanks.
sukhbir