Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Python identity operators: "is" and "is not" #180

@qingquan-li

Description

@qingquan-li

Sometimes a programmer wants to determine whether two variables are the same object. The programmer can use the identity operator, is, to check whether two operands are bound to a single object. The inverse identity operator, is not, gives the negated value of 'is'. Thus, if x is y is True, then x is not y is False.

Identity operators do not compare object values; rather, identity operators compare object identities to determine equivalence. Object identity is usually (Object identity is an implementation detail of Python. For the standard CPython implementation, identity is the memory address of the object) the memory address of an object. Thus, identity operators return True only if the operands reference the same object.

A common error is to confuse the equivalence operator "==" and the identity operator "is", because a statement such as if x is 3 is valid syntax and is grammatically appealing. Python may confusedly evaluate the statement x is 3 as True, but y is 1000 as False, when x = 3 and y = 1000. Python interpreters typically precreate objects for a small range of numbers to avoid constantly recreating objects for such small values. In the example above, an object for 3 was precreated and thus x references the same object as the literal. However, Python did not precreate an object for 1000. A good practice is to avoid using the identity operators "is" and "is not", unless explicitly testing whether two objects are identical.

The id() function can be used to retrieve the identifier of any object. If x is y is True, then id(x) == id(y) is also True.

$ python3
Python 3.8.10 (default, Mar 15 2022, 12:22:08) 
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> x = 3
>>> y = 1000

>>> x is 3
<stdin>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
True
>>> y is 1000
<stdin>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
False

>>> id(x)
9789024
>>> id(3)
9789024
>>> id(x) == id(3)
True

>>> id(y)
140230626062064
>>> id(1000)
140230626062096
>>> id(y) == id(1000)
False
jake@ubuntu:~$ python3
Python 3.8.10 (default, Mar 15 2022, 12:22:08) 
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> fruit_list = ['Apple', 'Avocado', 'Banana']
>>> fruit_name1 = 'Apple'
>>> fruit_name1 == fruit_list[0]
True
>>> fruit_name1 is fruit_list[0]
True
>>> id('Apple')
140637838967920
>>> id(fruit_name1)
140637838967920
>>> id(fruit_list[0])
140637838967920

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions