## Python Programming – Operators and Expressions

Special Operators

Python language offers some special type of operators like the identity operator

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.

 Operator symbol Name Example Output Description 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.

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 x1=10 y1=10 x2= ‘Program’ y2= ‘Program’ x3= [1, 2, 3] y3= [1, 2, 3] print(x1 is not y1) print(x2 is y2) print(x3 is y3) Output False True False

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.

Membership Operator

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]

 Operator symbol Name Example Output Description 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 otherwise.

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

 x=10 y=20 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’) else: print(‘y is available in the given list’) x=5 if( x in list): print(‘x is available in the given list’) else: print(‘x is not available in the given list’) Output x is not available in the given list y is not available in the given list x is available in the given list

Python Tutorial