Python provides two special types of operators: Identity operators and Membership operators. These are used for checking object identity and value membership, respectively.
Let’s understand how is
, is not
, in
, and not in
work with practical examples.
Example 1: Using is
for Identity Check
x = [1, 2, 3]
y = x
print(x is y)
Returns True
because both variables refer to the same object in memory.
Example 2: Using is not
a = [4, 5, 6]
b = [4, 5, 6]
print(a is not b)
Even though a
and b
have the same values, they are different objects. So the output is True
.
Example 3: Using in
with a List
fruits = ["apple", "banana", "mango"]
print("banana" in fruits)
Returns True
because "banana" is present in the list.
Example 4: Using not in
with a List
colors = ["red", "green", "blue"]
print("yellow" not in colors)
Returns True
because "yellow" is not in the list.
Example 5: in
with Strings
sentence = "Python is powerful"
print("power" in sentence)
Returns True
as "power" is a substring of the sentence.
Example 6: not in
with Strings
msg = "Welcome to Python"
print("Java" not in msg)
Returns True
since "Java" is not found in the string.
Example 7: in
with Dictionaries (keys)
person = {"name": "Alice", "age": 30}
print("age" in person)
Checks if "age" is a key in the dictionary. Returns True
.
Example 8: is
vs ==
x = [1, 2, 3]
y = [1, 2, 3]
print(x == y) # True (values are equal)
print(x is y) # False (different memory locations)
==
compares values, while is
compares identities.
Example 9: Identity Check with None
status = None
if status is None:
print("No status set")
Use is
to compare with None
, not ==
.
Example 10: Membership Check in Tuples
nums = (1, 3, 5, 7)
print(3 in nums)
Returns True
because 3 exists in the tuple.
Summary
is
: Checks if two variables point to the same object in memory.is not
: Checks if two variables do not refer to the same object.in
: Checks if a value exists in a sequence (string, list, tuple, etc.).not in
: Checks if a value does not exist in a sequence.
Understanding identity and membership operators helps you write cleaner, more readable Python code — especially when dealing with collections and object references.