Python Membership and Identity Operators
Last Updated :
07 May, 2024
There is a large set of Python operators that can be used on different datatypes. Sometimes we need to know if a value belongs to a particular set. This can be done by using the Membership and Identity Operators. In this article, we will learn about Python Membership and Identity Operators.
Python Membership Operators
The Python membership operators test for the membership of an object in a sequence, such as strings, lists, or tuples. Python offers two membership operators to check or validate the membership of a value. They are as follows:
Membership Operator
| Description
| Syntax
|
---|
in Operator
| Returns True if the value exists in a sequence, else returns False
| value in sequence
|
not in Operator
| Returns False if the value exists in a sequence, else returns True
| value not in sequence
|
Python IN Operator
The in operator is used to check if a character/substring/element exists in a sequence or not. Evaluate to True if it finds the specified element in a sequence otherwise False.
Example 1: Checking 'g' in string since Python is case-sensitive, returns False
'g' in 'GeeksforGeeks'
>>False
Example 2: Checking 'Geeks' in list of strings
'Geeks' in ['Geeks', 'For','Geeks']
>>True
Example 3: Checking 3 in keys of dictionary
dict1={1:'Geeks',2:'For',3:'Geeks'}
3 in dict1
>>True
Example 1: In this code we have initialized a list, string, set, dictionary and a tuple. Then we use membership in operator to check if the element occurs in the corresponding sequences or not.
Python
# initialized some sequences
list1 = [1, 2, 3, 4, 5]
str1 = "Hello World"
set1 = {1, 2, 3, 4, 5}
dict1 = {1: "Geeks", 2:"for", 3:"geeks"}
tup1 = (1, 2, 3, 4, 5)
# using membership 'in' operator
# checking an integer in a list
print(2 in list1)
# checking a character in a string
print('O' in str1)
# checking an integer in aset
print(6 in set1)
# checking for a key in a dictionary
print(3 in dict1)
# checking for an integer in a tuple
print(9 in tup1)
Output:
True
False
False
True
False
Example 2: Let us see the another example, but this time without using the ‘in’ operator:
Python
# Define a function() that takes two lists
def overlapping(list1, list2):
c = 0
d = 0
for i in list1:
c += 1
for i in list2:
d += 1
for i in range(0, c):
for j in range(0, d):
if(list1[i] == list2[j]):
return 1
return 0
list1 = [1, 2, 3, 4, 5]
list2 = [6, 2, 8, 9]
if(overlapping(list1, list2)):
print("overlapping")
else:
print("not overlapping")
Output
overlapping
Time Complexity:
The execution speed of the ‘in’ operator depends on the target object’s type.
- List: O(n), it becomes slower as the number of elements increases.
- Sets: O(1), it does not depend on the number of elements.
For dictionaries, the keys in the dictionary are unique values like set. So the execution is same as the set. Whereas the dictionary values can be repeated as in a list. So the execution of ‘in’ for values() is same as lists.
Python NOT IN Operator
The ‘not in’ Python operator evaluates to true if it does not find the variable in the specified sequence and false otherwise.
Example: In this code we have initialized a list, string, set, dictionary and a tuple. Then we use membership ‘not in’ operator to check if the element occurs in the corresponding sequences or not.
Python
# initialized some sequences
list1 = [1, 2, 3, 4, 5]
str1 = "Hello World"
set1 = {1, 2, 3, 4, 5}
dict1 = {1: "Geeks", 2:"for", 3:"geeks"}
tup1 = (1, 2, 3, 4, 5)
# using membership 'not in' operator
# checking an integer in a list
print(2 not in list1)
# checking a character in a string
print('O' not in str1)
# checking an integer in aset
print(6 not in set1)
# checking for a key in a dictionary
print(3 not in dict1)
# checking for an integer in a tuple
print(9 not in tup1)
Output:
False
True
True
False
True
The operators.contains() Method
An alternative to Membership ‘in’ operator is the contains() function. This function is part of the Operator module in Python. The function take two arguments, the first is the sequence and the second is the value that is to be checked.
Syntax: operator.contains(sequence, value)
Example: In this code we have initialized a list, string, set, dictionary and a tuple. Then we use operator module’s contain() function to check if the element occurs in the corresponding sequences or not.
Python
# import module
import operator
# using operator.contain()
# checking an integer in a list
print(operator.contains([1, 2, 3, 4, 5], 2))
# checking a character in a string
print(operator.contains("Hello World", 'O'))
# checking an integer in aset
print(operator.contains({1, 2, 3, 4, 5}, 6))
# checking for a key in a dictionary
print(operator.contains({1: "Geeks", 2:"for", 3:"geeks"}, 3))
# checking for an integer in a tuple
print(operator.contains((1, 2, 3, 4, 5), 9))
Output:
True
False
False
True
False
Python Identity Operators
The Python Identity Operators are used to compare the objects if both the objects are actually of the same data type and share the same memory location. There are different identity operators such as:
Identity Operator
| Description
| Syntax
|
---|
is Operator
| Returns True if both objects refers to same memory location, else returns False
| obj1 is obj2
|
is not Operator
| Returns False if both object refers to same memory location, else returns True
| obj1 is not obj2
|
Python IS Operator
The is operator evaluates to True if the variables on either side of the operator point to the same object in the memory and false otherwise.
Example: In this code we take two integers, lists and strings. Then used the ‘is’ operator to check each datatype’s identity.
Python
# Python program to illustrate the use
# of 'is' identity operator
num1 = 5
num2 = 5
lst1 = [1, 2, 3]
lst2 = [1, 2, 3]
lst3 = lst1
str1 = "hello world"
str2 = "hello world"
# using 'is' identity operator on different datatypes
print(num1 is num2)
print(lst1 is lst2)
print(str1 is str2)
print(str1 is str2)
Output:
We can see here that even though both the lists, i.e., ‘lst1’ and ‘lst2’ have same data, the output is still False. This is because both the lists refers to different objects in the memory. Where as when we assign ‘lst3’ the value of ‘lst1’, it returns True. This is because we are directly giving the reference of ‘lst1’ to ‘lst3’.
True
False
True
True
Python IS NOT Operator
The is not operator evaluates True if both variables on the either side of the operator are not the same object in the memory location otherwise it evaluates False.
Example: In this code we take two integers, lists and strings. Then used the ‘is not’ operator to check each datatype’s identity.
Python
# Python program to illustrate the use
# of 'is' identity operator
num1 = 5
num2 = 5
lst1 = [1, 2, 3]
lst2 = [1, 2, 3]
lst3 = lst1
str1 = "hello world"
str2 = "hello world"
# using 'is not' identity operator on different datatypes
print(num1 is not num2)
print(lst1 is not lst2)
print(str1 is not str2)
print(str1 is not str2)
Output:
False
True
False
False
Difference between ‘==’ and ‘is’ Operator
While comparing objects in Pyhton, the users often gets confused between the Equality operator and Identity ‘is’ operator. The equality operator is used to compare the value of two variables, whereas the identities operator is used to compare the memory location of two variables. Let us see the difference with the help of an example.
Example: In this code we have two lists that contains same data. The we used the identity ‘is’ operator and equality ‘==’ operator to compare both the lists.
Python
# Python program to illustrate the use
# of 'is' and '==' operators
lst1 = [1, 2, 3]
lst2 = [1, 2, 3]
# using 'is' and '==' operators
print(lst1 is lst2)
print(lst1 == lst2)
Output:
False
True
You can read more about it here.
Please Login to comment...