Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python - Identity Operators



Python Identity Operators

The identity operators compare the objects to determine whether they share the same memory and refer to the same object type (data type).

Python provided two identity operators; we have listed them as follows:

  • 'is' Operator
  • 'is not' Operator

Python 'is' Operator

The 'is' 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 "is" operator returns True.

Example of Python Identity 'is' Operator

a = [1, 2, 3, 4, 5]b = [1, 2, 3, 4, 5]c = a# Comparing and printing return valuesprint(a is c)print(a is b)# Printing IDs of a, b, and cprint("id(a) : ", id(a))print("id(b) : ", id(b))print("id(c) : ", id(c))

It will produce the followingoutput

TrueFalseid(a) :  140114091859456id(b) :  140114091906944id(c) :  140114091859456

Python 'is not' Operator

The 'is not' operator evaluates to True if both the operand objects do not share the same memory location or both operands are not the same objects.

Example of Python Identity 'is not' Operator

a = [1, 2, 3, 4, 5]b = [1, 2, 3, 4, 5]c = a# Comparing and printing return valuesprint(a is not c)print(a is not b)# Printing IDs of a, b, and cprint("id(a) : ", id(a))print("id(b) : ", id(b))print("id(c) : ", id(c))

It will produce the followingoutput

FalseTrueid(a) :  140559927442176id(b) :  140559925598080id(c) :  140559927442176

Python Identity Operators Examples with Explanations

Example 1

a="TutorialsPoint"b=aprint ("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 followingoutput

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

Thelist andtuple objects behave 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.

Example 2

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 followingoutput

id(a), id(b): 1552612704640 1552567805568a is b: Falseb 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".

Example 3

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

It will produce the followingoutput

140734682034984 140734682035016 140734682035048140734682034984 140734682035016 140734682035048

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

Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp