code part1:


code part2:


If I run the following code:

print name1 is name2

I get "True" for code part1
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:

Edited 3 Years Ago by slate

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(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)
>>> id(name2)
>>> name1 = [1,2,3]
>>> name2 = [1,2,3]
>>> id(name1)
>>> id(name2)

Edited 3 Years Ago by snippsat

This question has already been answered. Start a new discussion instead.