Python Identity Operators: Comparing Object Identities

thumb_up 1  ·  sell Python identity operators, Comparing object identities in Python, Using identity operators in Python

Python has two identity operators is and is not. Both return opposite Boolean values. The "in" operator evaluates to True if both the operand objects share the same memory location. The memory location of the object can be obtained by the "id()" function. If the id() of both variables is same, the "in" operator returns True (as a consequence, is not returns False).

 
a="TutorialsPoint" b=a print ("id(a), id(b):", id(a), id(b)) print ("a is b:", a is b) print ("b is not a:", b is not a)

It will produce the following output −

id(a), id(b): 2739311598832 2739311598832
a is b: True
b is not a: False

The list and tuple objects differently, which might look strange in the first instance. In the following example, two lists "a" and "b" contain same items. But their id() differs.

 
a=[1,2,3] b=[1,2,3] print ("id(a), id(b):", id(a), id(b)) print ("a is b:", a is b) print ("b is not a:", b is not a)

It will produce the following output −

id(a), id(b): 1552612704640 1552567805568
a is b: False
b is not a: True

The list or tuple contains the memory locations of individual items only and not the items itself. Hence "a" contains the addresses of 10,20 and 30 integer objects in a certain location which may be different from that of "b".

print (id(a[0]), id(a[1]), id(a[2])) print (id(b[0]), id(b[1]), id(b[2]))

It will produce the following output −

140734682034984 140734682035016 140734682035048
140734682034984 140734682035016 140734682035048

Because of two different locations of "a" and "b", the "is" operator returns False even if the two lists contain same numbers.

 

The End! should you have any inquiries, we encourage you to reach out to the Vercaa Support Center without hesitation.

 

Was this answer helpful?

Related Articles

description

Exploring Python's Key Characteristic

Python is a feature rich high-level, interpreted, interactive and object-oriented scripting language. This tutorial will list down some of…

arrow_forward
description

Comparing Python and C++

Both Python and C++ are among the most popular programming languages. Both of them have their advantages and disadvantages. In this…

arrow_forward
description

Creating a Python Hello World Program

This tutorial will teach you how to write a simple Hello World program using Python Programming language. This program will make use of…

arrow_forward
description

Python's Versatile Application Domains

Python is a general-purpose programming language. It is suitable for development of wide range of software applications. Over last few…

arrow_forward
description

Understanding the Python Interpreter

Python is an interpreter-based language. In a Linux system, Python's executable is installed in /usr/bin/ directory. For Windows, the…

arrow_forward
arrow_back « Back