Home  >  Article  >  Backend Development  >  In Python, when can I rely on using the is operator for identity testing?

In Python, when can I rely on using the is operator for identity testing?

王林
王林forward
2023-09-12 20:29:061121browse

In Python, when can I rely on using the is operator for identity testing?

Example

The is operator is an identity operator in Python. It is used to test the subject's identity. Let’s look at an example −

x = ["Paul","Mark"]
y = ["Paul","Mark"]
z = x

# Python IS operator
print(x is z)

Output

True

Suppose we consider another example where test a is b is equivalent to -

id(a) == id(b)

The key property of identity testing is that the object is always identical to itself, and a is a always returns True. Identity testing is usually faster than equality testing. Unlike equality tests, identity tests are guaranteed to return a Boolean value of True or False.

However, identity testing can only replace equality testing if the identity of the object is ensured. There are usually three situations where identity can be guaranteed:

  • Assignment creates a new name but does not change the object identity.

    After assigning new = old, it is guaranteed that new is old.

  • Putting an object into a container that stores object references does not change the object's identity.

    After list assignment, s[0] = x, ensures that s[0] is x.

  • If an object is a singleton, it means that only one instance of the object can exist. After assigning a = None and b = None, you can ensure that a and b are equal because None is a singleton.

Remember that identity testing should not be used to check constants such as int and str that are not guaranteed to be singletons. In the example below, we only get False -

Identity test on int

is translated as:

Identity test on int type

Example

Let’s test on integer elements -

a = 1000
b = 500
c = b + 500
print(a is c)

Output

False

String identity test

Example

An example of string identity testing −

a = 'Amit'
b = 'Am'
c = b + 'it'
print(a is c)

Output

False

Variable Type Identity Test

Example

In Python, lists are mutable. New instances of mutable containers are never the same; therefore the identity test returns False -

a = [10, 20, 30]
b = [10, 20, 30]
print(a is b)

Output

False

The above is the detailed content of In Python, when can I rely on using the is operator for identity testing?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete