Membership and Identity Operators in Python:

membership-and-identity-operators-in-python

Previously we learned about Logical Operators in Python while in this tutorial we learned about membership and identity operators in python.

In Python, we use membership operators to check if an element is present in a list or not while an identity operator is used to check whether a variable has the same values.

Using “in” operator:

The “in” operator returns True if the element is present in the list.

In the following code, we check if 3 is in the list my_list by using if statement. Since 3 is present in the list, the code inside the if statement block will execute and print “3 is in the list”.

my_list = [1, 2, 3, 4, 5]

if 3 in my_list:
    print("3 is in the list")

Using “not in” operator:

The “not in” operator returns True if the element is not present in the list.

In the following code, we check if 6 is not in the list my_list by using if statement. Since 6 is not present in the list, the code inside the if statement block will execute and print “6 is not in the list”.

my_list = [1, 2, 3, 4, 5]

if 6 not in my_list:
    print("6 is not in the list")

Identity operators:

In python, the identity operator determines whether two values have the same values and data type.

Using “is” operator:

The “is” operator returns True if the variables have the same identity. For example, x and y have the same value and have the same identity.

x = 5
y = 5
z = [1, 2, 3]

if x is y:
    print("x and y have the same identity")

Using “is not” operator:

The “is not” operator returns True if the variables do not have the same identity, as in the following equation. Here x is not equal to z so they do have not the same identity.

x = 5
y = 5
z = [1, 2, 3]

if x is not z:
    print("x and z do not have the same identity")

By combining these conditions with conditional statements, you can create more complex programs that make decisions based on multiple factors.

In the next tutorial, we are going to learn Truthness and Falsiness in python. Make sure to subscribe to us to learn python. If you have any questions, you can ask in a comment.


Discover more from Python Mania

Subscribe to get the latest posts sent to your email.

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

Related Articles:

Recent Articles:

0
Would love your thoughts, please comment.x
()
x

Discover more from Python Mania

Subscribe now to keep reading and get access to the full archive.

Continue reading