Web Analytics

Membership & Identity Operators

Beginner ~15 min read

Python provides intuitive operators for checking if values exist in sequences (in, not in) and for comparing object identity (is, is not). These make your code read almost like English!

The 'in' Membership Operator

The in operator checks if a value exists within a sequence like a list, string, tuple, set, or dictionary.

Sequence Type What 'in' Checks Example
ListItem in list'a' in ['a', 'b'] → True
StringSubstring in string'or' in 'world' → True
TupleItem in tuple1 in (1, 2, 3) → True
SetItem in set5 in {1, 5, 9} → True
DictionaryKey in dict (not value!)'name' in {'name': 'Jo'} → True
Output
Click Run to execute your code
Key Point: For dictionaries, in checks keys by default. Use value in dict.values() to check values, or value in dict.items() for key-value pairs.

The 'not in' Operator

The not in operator is the opposite of in - it returns True when a value is NOT found in the sequence.

Output
Click Run to execute your code
Performance Tip: Checking membership in a set is O(1) constant time, while lists are O(n). For large collections with many lookups, convert to a set first!

Identity Operators: 'is' and 'is not'

Identity operators check if two variables point to the same object in memory, not just if they have equal values.

Operator Description Example
isTrue if same objecta is b
is notTrue if different objectsa is not b
Output
Click Run to execute your code
Important: Don't use is to compare values! Use == for value comparison. is should primarily be used for checking None, True, or False.

Practical Uses of Identity Operators

The most common and important use of is is checking for None.

Output
Click Run to execute your code
Best Practice: Always use is None or is not None instead of == None. It's faster, safer, and the recommended Python style (PEP 8).

Common Mistakes

1. Using 'is' to compare values

# Wrong - may work sometimes, but unreliable!
if name is "Alice":  # Don't do this!
    print("Hello Alice")

# Correct - use == for value comparison
if name == "Alice":
    print("Hello Alice")

2. Checking dictionary values with 'in'

person = {"name": "Alice", "age": 30}

# Wrong - checks keys, not values!
if "Alice" in person:  # False!
    print("Found Alice")

# Correct - explicitly check values
if "Alice" in person.values():
    print("Found Alice")

3. Case-sensitive string membership

text = "Hello World"

# This fails because of case
if "hello" in text:  # False!
    print("Found")

# Correct - normalize case first
if "hello" in text.lower():
    print("Found")

4. Using == instead of 'is' for None

# Works but not recommended
if result == None:
    print("No result")

# Correct and preferred
if result is None:
    print("No result")

Exercise: Access Control

Task: Build an access control checker using membership operators.

Requirements:

  • Check if a user is in the guests list using in
  • Check if a user is in the banned list using in
  • Check if a user is NOT banned using not in
Output
Click Run to execute your code
Show Solution
guests = ["Alice", "Bob", "Charlie", "David"]
banned_users = ["Eve", "Mallory"]

name_to_check = "Bob"
banned_name = "Eve"

# 1. Check if name is in guests list
is_invited = name_to_check in guests
print(f"Is {name_to_check} invited? {is_invited}")  # True

# 2. Check if name is in banned list
is_banned = banned_name in banned_users
print(f"Is {banned_name} banned? {is_banned}")  # True

# 3. Check if name is NOT in banned list
is_safe = name_to_check not in banned_users
print(f"Is {name_to_check} safe? {is_safe}")  # True

Summary

  • in: Checks if a value exists in a sequence (list, string, tuple, set, dict keys)
  • not in: Checks if a value does NOT exist in a sequence
  • is: Checks if two variables point to the same object in memory
  • is not: Checks if two variables point to different objects
  • Use == for value comparison, is for identity/None checks
  • Performance: Set membership is O(1), list membership is O(n)

What's Next?

Congratulations on completing the Operators module! You now have all the tools to build expressions and make decisions in Python. Next, we'll learn about control flow with if statements - using these operators to direct your program's execution!