code part1:

name1="rahul"
name2="rahul"

code part2:

name1=[1,2,3]
name2=[1,2,3]

If I run the following code:

print name1 is name2

I get "True" for code part1
and
I get "False" for code part2

why? why the "reference" is same for name1 and name2 in "code part1" and different for name1 and name2 in "code part2??

Mutable objects cannot have the same identity. If you know what mutable means, you can understand that, it leads to a contradiction. Immutable objects can have the same id.

For immutable objects it is an implementation issue. With other python implementations (stackless, jython) you might get different results.

Object identity (is operator) should only be used on singletons (True,False), or on mutable objects . Use (and possibel override) equal (==) for other cases.

For further implementation details, see for example:
http://stackoverflow.com/questions/306313/python-is-operator-behaves-unexpectedly-with-integers

As a addition to slate explanation,do a test in interactive interpreter.

The 'is' operator is not another way to type '=='.

In most cases the use of == or != is what you want.
Normal way to use is are to test if something is identical to None like a is None or b is not None.

>>> help(id)
    Help on built-in function id in module __builtin__:

id(...)
    id(object) -> integer

Return the identity of an object.  This is guaranteed to be unique among
simultaneously existing objects.  (Hint: it's the object's memory address.)


>>> name1 = "rahul"
>>> name2 = "rahul"
>>> id(name1)
50933056
>>> id(name2)
50933056
>>> 
>>> name1 = [1,2,3]
>>> name2 = [1,2,3]
>>> id(name1)
52135216
>>> id(name2)
50904000
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.