Python Programming – Operators and Expressions
Python language offers some special type of operators like the identity operator
Identity operators compare the memory locations of two objects. They are used to check if two objects, values, or variables are located on the same part of the memory. Two variables that are equal do not imply that they are identical. The identity operators are listed in Table 3.7. Let us assume the value of x=10 and y=20.
|Is||is||X is y||False||Evaluates to true if the variables on either side of the|
|operator point to the same object and false otherwise.|
|Is not||Is not||X is not y||True||Evaluates to false if the variables on either side of the operator point to the same object and true otherwise.|
- Python Programming – Identity Operators
- Python Programming – Logical/Boolean Operators
- Quick Tip: Using Python’s Comparison Operators | Chaining Comparison Operators in Python
The Code 3.6. illustrates the use of identity operators.
Code: 3.6. Illustration of identity operators
|# program to illustrate the use of identity operators
Here, we see that xl and yl are integers of the same values, so they are equal as well as identical. Similarly, in the case of x2 and y2 (strings). But x3 and y3 are listed. They are not identical but equal. Since the list is mutable (can be changed), the interpreter locates them separately in memory although they are equal.
Python membership operators test for membership in a sequence. They are – used to examine whether a value or variable is found in a sequence (string, list, tuple, set, and dictionary). In a dictionary, we can only test for the presence of a key, not the value. Python language provides two membership operators in and not in presented in Table 3.8. Let y=15 and x is a list with the following values:
x = [10,20, 30, 40, 50]
|In||In||Y in x||False ( 0 )||Evaluates to true if it finds a variable in the specified sequence and false otherwise.|
|Not in||Not in||Y not in x||True ( 1 )||Evaluates to true if it does not finds a variable in the specified sequence and false
The programming example to illustrate membership operators is shown in Code 3.7.
Code: 3.7. Illustration of membership operators
#program to illustrate the use of membership operator
list,-[1,2,3,4,5];if( x in list):
print(‘x is available in the given list’)else:
print(‘x is not available in the given list’)if(y not in the list):
print(‘y is not available in the given list’)
x is not available in the given list