Membership & Identity Operators
-
This lesson explains Membership Operators (
in,not in) used to check if a value exists in a sequence, and Identity Operators (is,is not) used to compare memory locations of objects in Python.
1. Membership Operators
Membership operators are used to check whether a value exists in a sequence such as a list, tuple, string, or dictionary.
Membership Operators Example
Checks whether elements exist inside a list and a string.
fruits = ["apple", "banana", "mango"]
print("apple in fruits:", "apple" in fruits)
print("grape in fruits:", "grape" in fruits)
print("banana not in fruits:", "banana" not in fruits)
text = "Python"
print("'P' in text:", "P" in text)
print("'z' not in text:", "z" not in text)
2. Identity Operators
Identity operators are used to compare memory locations of two objects, not their values.
Identity Operators Example
Demonstrates how is and is not compare object identity.
a = [1, 2, 3]
b = a
c = [1, 2, 3]
print("a is b:", a is b)
print("a is c:", a is c)
print("a is not c:", a is not c)
Key Differences