Saturday, March 28, 2020

"Coder's Cat": Python: Is and ==

2020_03_28_the-difference-between-is-and-equal-in-python.org_20200328_234214.png

Figure 1: Photo by Rajiv Perera on Unsplash

== is comparing values

In Python, == compares the value of two variables and returns True as long as the values are equal.

>>> a = "hello cat"
>>> b = "hello cat"
>>> a == b
True

>>> b = "hello dog"
>>> a == b
False

is is comparing ids

is compares the ids of two variables.

That is, the actual comparing is id(a) == id(b), and it will return True only if the two variables point to the same object.

>>> a = "hello cat"
>>> b = a
>>> a is b
True
>>> b is a
True

>>> b = "hello cat"
>>> a is b
False

>>> id(a)
4512387504
>>> id(b)
4512387312

As we can see from the result, even the value of b is still the same with a, the variable of b is bind with a different object. So, a is b will return False.

An Exception

According to the above explanation, this code snippet should output False.

a = 2
b = 2
print (a is b)

But in fact, it will output True, because Python has a cache mechanism for small integers. The number between -5 and 256 will be cached. In this case since a and b have the same value, they point to the same object.

    The post Python: Is and == appeared first on Coder's Cat.



    from Planet Python
    via read more

    No comments:

    Post a Comment

    TestDriven.io: Working with Static and Media Files in Django

    This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...