Python has two types of operators, which are used to compare objects and find a value in things like a list, string, or set.
They are:
- Identity Operators (is, is not)
- Membership Operators (in, not in)
1. Identity Operators (is, is not)
Identity operators check whether two variables are pointing to the same object in memory or not.
They do not compare values; they just check whether both have the same address or not.
is
→ Returns True if both variables are pointing to the same object.is not
→ Returns True if both are pointing to different objects.
Example:
list1 = [1, 2, 3]
list2 = [1, 2, 3]
list3 = list1 # list3 and list1 are the same object
print(list1 is list2) # False - different objects
print(list1 is list3) # True - same object
print(list1 is not list2) # True
An important thing:
If you want to check if a variable is None
or not, then using is None
is the best and fastest way.
Remember:
- If you want to compare values then use
==
. - If you want to check if both are exactly the same object then use
is
.
2. Membership Operators (in, not in)
These operators check whether a value is in a sequence (such as a list, string, tuple, or set) or not.
in
→ Returns True if the value is found in the sequence.not in
→ Returns True if the value is not found in the sequence.
Example 1: List and String
fruits = ["apple", "banana", "cherry"]
text = "Hello Python"
print("apple" in fruits) # True
print("grape" not in fruits) # True
print("Python" in text) # True
The in
operator can find substrings in a string, and also elements in a list/tuple.
Example 2: Dictionary
With a dictionary, the in
operator finds keys, not values.
data = {"a": 1, "b": 2}
print("a" in data) # True - key exists
print(1 in data) # False - does not check values by default
print(1 in data.values()) # True - values() has to be used to check values
3. Understand the difference quickly
Things | Identity Operators (is, is not) | Membership Operators (in, not in) |
---|---|---|
What do they do | Check if both are the same object or not | Check if a value is in a collection or not |
Where do they work | On any Python object | Sequence (list, tuple, string, dict, set) |
How do they compare | Memory address | Value presence |
Example | x is y | "apple" in fruits |
Next Lession: if, elif, else Conditions in Python