top of page
BlogPageTop

What is "is" in Python?


The operators is and is not test for object identity. x is y is true if and only if x and y are the same object (object location in memory is same). Object identity is determined using the id() function. x is not y yields the inverse truth value.

It’s easy to understand if I compare this operator with equality operator.

  • is and is not compares the object reference. Check for identity.

  • == and != compares the object value. Check for equality.

For example, if you consider integer objects (excluding integers from -5 to 256),

>>> A=9999 
>>> B=9999 
>>> A == B, A is B
(True, False
>>> A, B
(9999, 9999) 
>>> id(A), id(B)
(4452685328, 4452686992)

Python stores integer objects as single object between range -5 to 256 so the identity is same.

>>> A=99
>>> B=99 
>>> A == B, A is B
(True, True
>>> A, B
(99, 99) 
>>> id(A), id(B)
(4404392064, 4404392064)

Lets see behavior of other immutable objects like int & float, string, tuples and boolean:

>>> 1 == 1.0, 1 is 1.0
(True, False
>>> 1 == 1, 1 is 1
(True, True
>>> 'A' == 'A', 'A' is 'A'
(True, True
>>> (1,2) == (1,2), (1,2) is (1,2)
(True, True
>>> True == True, True is True
(True, True)

What about mutable objects - list, set, dict? Behavior is totally different.

>>> [1,2] == [1,2], [1,2] is [1,2]
(True, False
>>> {1,2} == {1,2}, {1,2} is {1,2}
(True, False
>>> {'k1':1} == {'k1':1}, {'k1':1} is {'k1':1}
(True, False)

is operator is used only when you want to compare the object identity, for regular comparison equality operator is used.

Comentários


Want to share your thoughts about this blog?

Disclaimer: Please note that the information provided on this website is for general informational purposes only and should not be taken as legal advice. Dataneb is a platform for individuals to share their personal experiences with visa and immigration processes, and their views and opinions may not necessarily reflect those of the website owners or administrators. While we strive to keep the information up-to-date and accurate, we make no representations or warranties of any kind, express or implied, about the completeness, accuracy, reliability, suitability, or availability with respect to the website or the information, products, services, or related graphics contained on the website for any purpose. Any reliance you place on such information is therefore strictly at your own risk. We strongly advise that you consult with a qualified immigration attorney or official government agencies for any specific questions or concerns related to your individual situation. We are not responsible for any losses, damages, or legal disputes arising from the use of information provided on this website. By using this website, you acknowledge and agree to the above disclaimer and Google's Terms of Use (https://policies.google.com/terms) and Privacy Policy (https://policies.google.com/privacy).

bottom of page