Membership operators are used to check whether a value exists in a sequence such as a string, list, tuple, set, or dictionary.
| Operator | Meaning |
|---|---|
in |
Returns True if value is present |
not in |
Returns True if value is not present |
in Operatortext = "Python"
print("P" in text)
print("z" in text)
Output
True
False
not in Operatornumbers = [1, 2, 3, 4]
print(5 not in numbers)
print(2 not in numbers)
Output
True
False
nums = [10, 20, 30]
print(20 in nums)
print("Py" in "Python")
student = {"name": "Rahul", "age": 20}
print("name" in student)
Explanation
Identity operators are used to compare whether two variables refer to the same object in memory.
| Operator | Meaning |
|---|---|
is |
True if both variables refer to same object |
is not |
True if objects are different |
is Operatora = 10
b = 10
print(a is b)
is not Operatorx = [1, 2]
y = [1, 2]
print(x is not y)
== and isx = [1, 2]
y = [1, 2]
print(x == y) # compares values
print(x is y) # compares memory
Output
True
False
a = [1, 2]
b = a
print(a is b)
Output
True
is checks object identity (memory location)== checks value equalityin, not inis, is not