Python Basics — Identity & Membership Operators
Identity & Membership Operators
Python has two special categories of operators: identity operators (is, is not) that check if two variables refer to the same object, and membership operators (in, not in) that check if a value exists in a sequence.
Identity Operators
| Operator | Meaning | Example |
|---|---|---|
is |
Same object in memory | x is y |
is not |
Different objects | x is not y |
is vs ==
This is one of the most important distinctions in Python:
==checks if two values are equal (same content)ischecks if two variables point to the same object in memory
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a == b) # True (same content)
print(a is b) # False (different objects!)
print(a is c) # True (c points to the same object as a)
print(id(a)) # e.g., 140234866423056
print(id(b)) # e.g., 140234866423120 (different!)
print(id(c)) # e.g., 140234866423056 (same as a!)
Integer Caching
Python caches small integers (-5 to 256) for performance, so is may return True for small numbers:
a = 256
b = 256
print(a is b) # True (cached — same object)
a = 257
b = 257
print(a is b) # False (not cached — different objects)
# Note: behavior may vary in interactive mode vs scripts
Rule: Always use == for value comparison. Only use is with None, True, False.
String Interning
Python also interns (caches) some strings:
a = "hello"
b = "hello"
print(a is b) # True (Python interns simple strings)
a = "hello world"
b = "hello world"
print(a is b) # May be False (spaces prevent interning)
When to Use is
# ✅ Correct uses of "is"
x = None
if x is None:
print("No value")
if x is not None:
print("Has a value")
# ✅ Checking singletons
print(True is True) # True
print(False is False) # True
Membership Operators
| Operator | Meaning | Example |
|---|---|---|
in |
Value exists in sequence | "a" in "apple" |
not in |
Value does not exist | 5 not in [1, 2, 3] |
Membership in Strings
print("a" in "apple") # True
print("app" in "apple") # True (substring check)
print("z" in "apple") # False
print("A" in "apple") # False (case-sensitive)
print("x" not in "apple") # True
Membership in Lists
fruits = ["apple", "banana", "cherry"]
print("banana" in fruits) # True
print("grape" in fruits) # False
print("grape" not in fruits) # True
Membership in Tuples
colors = ("red", "green", "blue")
print("green" in colors) # True
print("yellow" in colors) # False
Membership in Dictionaries
With dictionaries, in checks keys, not values:
user = {"name": "Alice", "age": 25}
print("name" in user) # True (checks keys)
print("Alice" in user) # False (Alice is a value, not a key)
print(25 in user) # False (25 is a value, not a key)
# To check values, use .values()
print("Alice" in user.values()) # True
print(25 in user.values()) # True
Membership in Sets
Sets provide O(1) membership testing — much faster than lists for large collections:
valid_codes = {100, 200, 301, 404, 500}
print(404 in valid_codes) # True
print(999 in valid_codes) # False
Practical Examples
# Input validation
valid_commands = ["start", "stop", "restart", "status"]
user_input = "start"
if user_input in valid_commands:
print(f"Executing: {user_input}")
else:
print(f"Unknown command: {user_input}")
# Executing: start
# Check file extension
filename = "report.pdf"
if filename.endswith((".pdf", ".doc", ".txt")):
print("Document file")
# Document file
# Password character check
password = "MyP@ss123"
has_digit = any(c.isdigit() for c in password)
has_special = any(c in "!@#$%^&*" for c in password)
print(f"Has digit: {has_digit}, Has special: {has_special}")
# Has digit: True, Has special: True
Performance Comparison
| Collection | in Speed |
Best For |
|---|---|---|
list |
O(n) — slow for large lists | Small collections |
tuple |
O(n) — similar to list | Small, fixed data |
set |
O(1) — very fast | Large lookup tables |
dict |
O(1) — very fast | Key lookups |
str |
O(n) — substring search | Text searching |
Common Mistakes
| Mistake | Example | Fix |
|---|---|---|
is for value comparison |
if x is 5: |
Use if x == 5: |
in checks dict keys only |
"Alice" in user → False |
Use "Alice" in user.values() |
Case-sensitive in |
"A" in "apple" → False |
Normalize: "a" in "apple".lower() |
Summary
ischecks identity (same object in memory),==checks equality (same value)- Use
isonly withNone,True,False— use==for everything else - Python caches small integers (-5 to 256) — don’t rely on
isfor numbers intests membership in strings, lists, tuples, dicts, and sets- With dicts,
inchecks keys — use.values()to check values - Sets provide the fastest membership testing — O(1) vs O(n) for lists
Next up: Practice Exercises →