- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
When can I rely on identity tests with the is operator in Python?
Example
The is operator is an identity operator in Python. It tests for object identity. Let us see an example −
x = ["Paul","Mark"] y = ["Paul","Mark"] z = x # Python IS operator print(x is z)
Output
True
Let’s say we consider another example, wherein the test a is b is equivalent to −
id(a) == id(b)
The key property of an identity test is that an object is always identical to itself, a is a always returns True. Identity tests are usually faster than equality tests. And unlike equality tests, identity tests are guaranteed to return a boolean True or False.
However, identity tests can only be substituted for equality tests when object identity is assured. Generally, there are three circumstances where identity is guaranteed −
Assignments create new names but do not change object identity.
After the assignment new = old, it is guaranteed that new is old.
Putting an object in a container that stores object references does not change object identity.
After the list assignment s[0] = x, it is guaranteed that s[0] is x.
If an object is a singleton, it means that only one instance of that object can exist. After the assignments a = None and b = None, it is guaranteed that a is b because None is a singleton.
Remember, identity tests should not be used to check constants such as int and str which aren’t guaranteed to be singletons. In the below examples, we only get False −
Identity test on int
Example
Let us test on integer elements −
a = 1000 b = 500 c = b + 500 print(a is c)
Output
False
Identity test on strings
Example
An example for identity tests on strings −
a = 'Amit' b = 'Am' c = b + 'it' print(a is c)
Output
False
Identity test on Mutable Type
Example
In Python, Lists are mutable. The new instances of mutable containers are never identical; therefore identity test returns False −
a = [10, 20, 30] b = [10, 20, 30] print(a is b)
Output
False