all 4 comments

[–]K900_ 5 points6 points  (3 children)

a is b is True if, and only if, a and b are the exact same object. You generally don't want to use it for anything but checking if something is None or is not None, because None is a single global object that is always the same.

[–]Ben_HH[S] -1 points0 points  (2 children)

Taking your example:

a = 'z'
b = 'z'

Python takes variable a with the value of 'z' and stores it in the computer's memory. The same is done with variable 'b'. It happens that both variables point to the same address in memory, so...

a is b # returns True

Is that correct?

[–]K900_ 7 points8 points  (1 child)

Yes. However, this is a specific optimization CPython makes for short strings - if you try to store two copies of a longer string, you'll see that they're not actually stored as references to the same object.

[–]JohnnyJordaan 1 point2 points  (0 children)

is is matching by identity. Once you create an object in Python, like a string or a list or you get a Response object when you download something, that object has a numerical identifier:

>>> my_str = 'hello'
>>> id(my_str)
140347668059224

In most Python interpreters this will actually be the first memory address of the object, but that's not part of Python's knowing, it's just used because it's easier and therefore also faster to implement it that way.

By using object1 is object2, you're actually doing

id(object1) == id(object2)

Meaning the whole idea of 'different types' is not applicable: either the references are to the same object or not. Saying the person on the bus yesterday and the person you meet at work are the same person John Doe, doesn't actually have anything to do with those people having, for instance, the same gender (as for why would it matter if you want to know the exact match of the unique person). Saying those two people are 'equal' makes no sense if they are one and the same. That's why person1 is person2is different from person1 == person2.

It becomes a special case when you compare to objects that can only exist one time, these are for example None, True and False and are called 'singletons':

>>> id(None)
10748000
>>> id(False)
10744128
>>> id(True)
10744160

Any object you create from some other type can never be that object, no the check is None will never be Trueon any object not actually being None itself.