"is" operator behaviour in python


Hi ,
This querry is not w.r.t exercise but on "is" oprator in python .
Per my knowledge the operators "is" and "is not" test for object identity.
I am using 3.x version of python and observing different behaviour when I execute from python prompt and executing thru program.
Please help me understanding why there is different behaviour.
Below is the o/p for your reference , captured from python prompt and thru program.

Below is the output of python prompt:
>>> a = "hello world"
>>> b = "hello world"
>>> print id(a),id(b)
34168608 34168648
>>> print hash(a),hash(b)
-1500746465 -1500746465
>>> a is b

Below is the program and  o/p:
a = "hello world"
b = "hello world"
print id(a),id(b)
print hash(a),hash(b)
if a is b:print "Both ids are same"
else: print "Both ids are different"

>>> ================================ RESTART ================================
34144848 34144848
-1500746465 -1500746465
Both ids are same


Hi @kiranurs,

When two str objects are equivalent, Python will often, but not always, make them be the same object. Even when executing in a program, two strings that are identical are sometimes different objects. It might depend upon efficiency. See below, executed in IDLE 3.6 ...

a = "hello"
b = "world"
c = a + " " + b
d = "hello world"
print(c == d)
print(c is d)

Output ...


In this case, the strings are equivalent, but not identical.


Thanks for the reply.
In my case even though couple of runs thru program,
gives same id's for the identical strings.
But however my original querry is still alive. Why there is a difference in the o/p when we run
same piece of code thru pompt and thru program?.
My expectation here is the behaviour shud be the same, which is not getting in this case.

Also in your code which is slightly different from my case.
You are using concatenation of two strings resulting
in different ids, but the hash value of both c and d are same.
Below is the IDs and hash value of your code.

id(a) = 140142176
id(b) = 140141344
id(c) = 140101296
id(d) = 140101456

Hash values.
hash(a) = -444994147
hash(b) = 1648043488
hash (c) = -882791957
hash(d) = -882791957


Perhaps some designers of Python interpreters can answer that. However the difference in behavior does not run counter to any definitions or policies related to the Python language.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.