Python Special operators

Python Special operators

Python language offers some special type of operators like the identity operator or the membership operator. They are described below with examples.

Identity operators

“is” and “is not” are the identity operators in Python. They are used to check if two values (or variables) are located on the same part of the memory. Two variables that are equal does not imply that they are identical.

Operator Meaning Example
is True if the operands are identical (refer to the same object) x is True
is not True if the operands are not identical (do not refer to the same object) x is not True

Example : Identity operators in Python

x1 = 5
y1 = 5
print(x1 is y1)
# Output: true
print(x1 is not y1)
# Output: False

x1 = 5
y1 = 5
print(x1 is y1)
print(x1 is not y1)

Output:

True
False
>>> 

x2 = ‘Hello’
y2 = ‘Hello’
print(x2 is y2)
# Output: True
print(x2 is not y2)
# Output: False

Here, we see that x1 and y1 are integers of the same values, so they are equal as well as identical. The same is the case with x2 and y2 (strings).

x2 = 'Hello'
y2 = 'Hello'
print(x2 is y2)
print(x2 is not y2)

Output:

True
False
>>> 

Membership operators

“in” and “not in” are the membership operators in Python. They are used to test 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.

Operator Meaning Example
in True if value/variable is found in the sequence 5 in x
not in True if the value/variable is not found in the sequence 5 not in x

Examples of Membership operators in Python

Example:1:
x = ‘Hello world’
print(‘H’ in x)
# Output: True
print(‘hello’ not in x)
# Output: True
print(‘w’ in x)
# Output: True
print(‘Hello’ in x)
# Output: True
Here, ‘H’ is in x but ‘hello’ is not present in x (remember, Python is case sensitive).

x = 'Hello world'
print('H' in x)
print('hello' not in x)
print('w' in x)
print('Hello' in x)

Output:

True
True
True
True
>>> 

In a dictionary we can only test for presence of key, not the value.

//y={key:value,key:value}
y = {1:’a’,2:’b’}
print(1 in y)
# Output: True
print(‘a’ in y)
# Output: False

y = {1:'a',2:'b'}
print(1 in y)
print('a' in y)

Output:

True
False
>>> 

In a dictionary we can only test for presence of key, not the value.

>>> y = {1:’a’,2:’b’}
Here 1 is key and ‘a’ is the value in dictionary y.
Here 2 is key and ‘b’ is the value in dictionary y.
We can check for key and not value.
>>> print(1 in y)
True
>>> print(‘a’ in y)
False
>>> print(2 in y)
True
>>> print(‘b’ in y)
False
>>> print(3 in y)
False
>>>

Hence, ‘a’ in y returns False.
Hence, ‘b’ in y returns False.