Page 70 - tp_Modula_v2.0
P. 70
Identity Operators
Identity operators in Python are used to compare the memory locations of two objects to check
whether they refer to the same object. There are two identity operators:
is: Returns True if two variables point to the same object in memory.
is not: Returns True if two variables do not point to the same object in memory.
Program 8: To use identity operators.
Program8.py
File Edit Format Run Options Window Help
# Example of Identity Operator with Strings
str1 = "hello"
str2 = "hello"
str3 = "he" + "llo" # Created dynamically
# Using 'is'
print(str1 is str2) # Output: True (Both refer to the same memory
location due to string interning)
print(str1 is str3) # Output: True (Python optimizes and interns this
case)
# Using 'is not'
print(str1 is not str2) # Output: False (They are the same object)
print(str1 is not str3) # Output: False (They are the same object)
On running the above program, you will get the following output:
Output
True
True
False
False
Membership Operators
Membership operators are used to check if a particular character exists in the given string or not.
There are two types of membership operators:
‘in’ operator: It returns true if a characters/substring exist in the given string.
‘not in’ operator: It returns true if a characters/substring does not exist in the given
string.
Program 9: To use membership operators.
Program9.py
File Edit Format Run Options Window Help
text = "Hello, Python!"
print("Hello" in text)
print("Python" not in text)
68 Touchpad MODULAR (Version 2.0)

