Identity Operators:
+-----------+--------------------------------+
| is | is having the same id()? |
| is not | is not having the same id()? |
+-----------+--------------------------------+
Using identity operators we can check if two objects share the same memory location. We can check this with the id() function also. The expression a is b results in True if id(a) is equal to id(b).
Example:
a = 5
b = 5
if a is b:
print("a and b have same identity:")
print("id:",id(a),"and",id(b))
else:
print("a and b have different identities:")
print("id:",id(a),"and",id(b))
b = 10
if a is b:
print("a and b have the same identity: ")
print("id:",id(a),"and",id(b))
else:
print("a and b have different identities:")
print("id:",id(a),"and",id(b))
Output:
a and b have same identity:
id: 140719525389264 and 140719525389264
a and b have different identities:
id: 140719525389264 and 140719525389424
We can also find the type of an object using identity operators. The following example converts the variable code to a string if code is not of type string.
code = 91
if type(code) is not str:
print("Country code: +" + str(code))
Output:
Country code: +91
.
+-----------+--------------------------------+
| is | is having the same id()? |
| is not | is not having the same id()? |
+-----------+--------------------------------+
Using identity operators we can check if two objects share the same memory location. We can check this with the id() function also. The expression a is b results in True if id(a) is equal to id(b).
Example:
a = 5
b = 5
if a is b:
print("a and b have same identity:")
print("id:",id(a),"and",id(b))
else:
print("a and b have different identities:")
print("id:",id(a),"and",id(b))
b = 10
if a is b:
print("a and b have the same identity: ")
print("id:",id(a),"and",id(b))
else:
print("a and b have different identities:")
print("id:",id(a),"and",id(b))
Output:
a and b have same identity:
id: 140719525389264 and 140719525389264
a and b have different identities:
id: 140719525389264 and 140719525389424
We can also find the type of an object using identity operators. The following example converts the variable code to a string if code is not of type string.
code = 91
if type(code) is not str:
print("Country code: +" + str(code))
Output:
Country code: +91
.
No comments:
Post a Comment