1

The is keyword in python is described like that: is is used in Python for testing object identity. While the == operator is used to test if two variables are equal or not, is is used to test if the two variables refer to the same object.

It returns True if the objects are identical and False if not.

>>> True is True
True
>>> False is False
True
>>> None is None
True

We know that there is only one instance of True, False and None in Python, so they are identical.

>>> [] == []
True
>>> [] is []
False
>>> {} == {}
True
>>> {} is {}
False

An empty list or dictionary is equal to another empty one. But they are not identical objects as they are located separately in memory. This is because list and dictionary are mutable (value can be changed).

>>> '' == ''
True
>>> '' is ''
True
>>> () == ()
True
>>> () is ()
True

Unlike list and dictionary, string and tuple are immutable (value cannot be altered once defined). Hence, two equal string or tuple are identical as well. They refer to the same memory location.

Till now there is no problem. My issue is that I have two instances of two variables as string type

a = 'yasser'
b = 'yasser'
a is b

This code returns True while

a = 'yasser!'
b = 'yasser!'
a is b

This returns False althought these are of string types. Any explanation..?

YasserKhalil
  • 9,138
  • 7
  • 36
  • 95
  • 2
    "Unlike list and dictionary, string and tuple are immutable (value cannot be altered once defined). Hence, two equal string or tuple are identical as well." **this is not a valid inference**. Stop right there and forget that entirely. The CPython runtime *happens* to optimize some literal expressions that result in immutable objects, but that is an implementation detail, not some language guarantee. Indeed, it should *surprise* you that `() is ()` etc. – juanpa.arrivillaga Feb 16 '21 at 18:07
  • 2
    So, it is *an implementation detail* that CPython will intern strings in literal expressions that are valid identifiers, i.e `'yasser'`, but not strings that are not, e.g. `'yasser!'`, Again, this is an implementation detail *that you should never even consider* when writing your code. Your faulty assumption is that immutable objects with the same value should be identical, that is simply a false assumption. – juanpa.arrivillaga Feb 16 '21 at 18:08
  • 2
    However, the Python *language* does guarantee that `None`, `True`, and `False` are singletons. These are special cases, though. – juanpa.arrivillaga Feb 16 '21 at 18:11
  • @juanpa.arrivillaga I wish could have written that! – BoarGules Feb 16 '21 at 21:08

1 Answers1

0

The 'is' keyword evaluates to true if the true arguments are from the same object. In the cases you had above, all of the ones that evaluate to true are from the same object, however, while those two strings are identical, they are not the same object. You can read more about it here.

tofstie
  • 21
  • 2