In this article, we will learn about membership and identity operators in Python which are in
, not in
, is
and is not
operators. These operators are used to check if a given data element is part of a sequence or not and in the case of the identity operator, whether a given element is of a certain type. Let's start with the membership function first.
Whether you're new to Python or just looking to refresh your knowledge, this article will provide a comprehensive guide to using membership and identity operators in Python.
Python Membership Operators
These operators help validate whether a given element is present in or is a member of the given sequence of data. This sequence of data can be a list, string, or tuple.
in
Operator:
It checks whether the value is present in the sequence of data or not. It evaluates to true value if the element is present in the sequence and to false value if the element is absent from the sequence. Let's take an example to understand its usage,
my_new_list = [1,2,3,'a']
# loop around the list
for i in my_new_list:
print(i)
Output:
1
2
3
a
The in
operator in the for
loop allows the variable i
to reference every element present in the list iterated by the loop. You must be thinking that the in
operator is used to check if an element is present in a sequence or not, but what exactly is happening here? Well, the in
operator performs differently when it is used in different contexts, i.e in a loop and in a conditional statement like if
statement.
The statement x in y
calls y.__contains__(x)
if y
has a __contains__
member function otherwise x in y
will try to iterate through the y.__iter__()
function to find x
or it calls the y.__getitem__(x)
if the iter method doesn't exist.
The y.__getitem__(x)
works similar to y is x[i] or y == x[i],
where 'i' has to fulfill the condition of being a non-negative integer (index). If this condition on 'i' fails, it raises an IndexError
exception.
But when we use in operator with the for loop, then it is a marker that separates the loop-index variable from the iterable object. Hence we can say that the above example is not actually utilizing the in
operator, so let's take another example,
first_list = [1,2,3,'a']
second_list = ['a','b','c',10]
# loop around the list
for i in first_list:
if i in second_list:
print(i,"is present in both lists")
Output:
a is present in both lists
In the example above we can see the actual use of the in
operator which is used to check if a given element is present in a sequence or not.
One important thing to remember is that empty strings are always considered to be a part/substring of a string. Here is an example to demonstrate the same:
'' in 'abc123'
Output:
True
not in
Operator:
This operator checks for the absence of a value in a sequence. This is the exact opposite of the in
operator. It evaluates to true when the element is not found or absent from the sequence and returns false when the element is found in the data sequence. The element to be searched for is the left operand and the sequence in which it is searched for is the right-hand operand.
my_new_list = [1,2,3, 'a']
special = 'Studytonight'
if special not in my_new_list:
print('True')
Output:
True
special
not in my_new_list
returns the negation of the in
operator. The if
condition checks whether or not the variable special
is present in the list. Since the element special
isn't present in the list, it returns true.
Python Identity Operators
These operators help in determining whether a value belongs to a certain class or a certain type, i.e they help in determining the identity of the object. It is useful in finding out the data type a variable holds. The identity of an object can be determined by using the id()
function. For example,
list = [1,2,3,4,5]
print(id(list))
This will print a unique id representing the identity of that particular python object, in this case, a list.
is
Operator:
It helps determine if a certain object belongs to a certain class/data type or if two operands are of the same object or not. We use this operator when in any condition we have to check for an object's identity. If the type/class of the operand on either side of the is
operator is the same, it evaluates to a true value, else to a false value.
A basic example of using the is
operator would be to match to objects, for example,
list1 = [1, 2, 3, 'a']
list2 = [10, 20, 30]
# using is operator
if list1 is list2:
print("True")
else:
print("False")
The above python script will print False because list1
and list2
are not the same, they occupy different memory locations and have different identities, we can check that using the id()
function.
Let's modify the above code and assign list1
to list2
and then use the is
operator to check if its able to find out that both the objects are same,
list1 = [1, 2, 3, 'a']
list2 = list1
# using is operator
if list1 is list2:
print("True")
else:
print("False")
In this case, the output will be True, because list2
is also referencing the same list which is referenced by the list1
variable.
We can also use the is
operator with other functions like the type()
function to check whether two Python objects are of the same type or not.
my_new_list = [1, 2, 3, 'a']
my_new_tuple = (1, 2, 3, 'a')
type(my_new_list)
type(my_new_tuple)
if type(my_new_list) is type(my_new_tuple):
print('They belong to same type')
else:
print("They don't belong to same type")
Output:
They don't belong to same type.
Since the data structure list is not the same as the data structure tuple, hence the else block is executed.
is not
Operator:
It behaves in the exact opposite way of the is
operator. It checks whether values on either side of the is not
operator are not the same or the same. If they are not the same, it evaluates to a true value, else to a false value.
Again, we can use this with the type()
function to compare data types of different Python objects:
my_new_list = [1,2,3, 'a']
my_new_tuple = (1,2,3, 'a')
type(my_new_tuple)
if type(my_new_list) is not type(my_new_tuple):
print('True!, They are not of the same type')
else:
print("False, They are the same type")
Output:
True!, They are not of the same type
Since a tuple and a list are not the same and the is not
operator checks for their inequality, it returns True.
Let's take another example where we will compare two operands to see if they are the same object or not.
my_list_one = [1, 2, 3]
my_list_two = [1, 2, 3]
my_list_one is not my_list_two
Output:
True
This is because both lists refer to different objects which are present at different locations in memory.
Conclusion
The prefix 'b' in a string holds considerable significance in Python, affecting the way the string is interpreted and encoded. Whether it's for handling binary data, working with specific encodings, or maintaining data integrity, understanding the implications of the 'b' prefix is essential for Python developers.
The membership and identity operators come in handy while looking to check for certain elements in a sequence of data and to check the identity of the data respectively. The identity operators can be used with the type() function for checking if a variable is of a certain type or of a certain class before performing any operation on it.
Python's flexibility shines through its ability to handle various data types, and the 'b' prefix adds another layer of versatility to the language's string manipulation capabilities.
Frequently Asked Questions(FAQs)
1. What are membership and identity operators in Python?
Membership and identity operators in Python are used to test if a value is a member of a sequence or if two objects refer to the same object in memory. The membership operators are "in" and "not in", while the identity operators are "is" and "is not".
2. How does the "in" operator work in Python?
The "in" operator in Python returns "True" if a value is found in a sequence, and "False" if it is not found. For example, "5 in [1, 2, 3, 4, 5]" would return "True".
3. What is the difference between the "is" and "==" operators in Python?
The "is" operator in Python tests for object identity, meaning it checks if two objects refer to the same object in memory. The "==" operator, on the other hand, tests for equality, meaning it checks if two objects have the same value.
4. How can I use the "not in" operator in Python?
The "not in" operator in Python works similarly to the "in" operator but returns "True" if a value is NOT found in a sequence. For example, "5 not in [1, 2, 3, 4, 5]" would return "False".
You may also like: