Membership and identity
- Python course
- Beginner
- Lesson 28/116
- 4 min
Learn in and is operators.
Membership and identity operators
The in operator checks whether a value is in a collection. is checks whether two variables point to the same object.
print(3 in [1, 2, 3]) # True
print("a" in "ali") # True
print(a is None) # None checkin works with lists, strings, tuples and dicts. is is for identity; for value equality use ==.
is vs ==
is checks whether two variables point to the same object (identity). == checks whether the values are equal.
a = [1, 2]
b = [1, 2]
print(a == b) # True (same value)
print(a is b) # False (different object)a and b have the same value but are different objects. So == is True, is is False. Using is None is the right way to check None.
Practice Print membership
Assign numbers = [1, 2, 3, 4]. Print print(3 in numbers) and print(5 in numbers).
Starter code
# Membership checkSample solution
numbers = [1, 2, 3, 4]
print(3 in numbers)
print(5 in numbers)Expected output
True False
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Membership check
print(3 ____ [1, 2, 3])
print(3 in [1, 2, 3])
Explanation: We check whether a value is in a collection with in.
2 Which is true?
- is and == are the same
- is checks value, == checks identity
- is checks identity, == checks value Correct answer
- is is only for numbers
Explanation: is checks identity, == checks value.
3 Match the operators
| Term | Meaning |
|---|---|
in |
Membership |
is |
Identity |
== |
Value equality |
not in |
Not a member |