Popular Searches
Popular Course Categories
Popular Courses

Understanding Membership and Identity Operators

Understanding Membership and Identity Operators

Operators and Expressions in Python

Understanding Membership and Identity Operators in Python

Course: Python Training Course

Topic: Understanding Membership and Identity Operators

Course Link: Python Training Course at JustAcademy

Demo Registration: Register for a Free Course Demo

JustAcademy Homepage: Visit JustAcademy


1. Introduction to Membership and Identity Operators

Python provides several operators for comparing values and checking relationships between objects. Membership operators determine whether an element exists inside a collection or sequence, while identity operators determine whether two references point to the same object in memory.

Membership and identity operators are commonly used with strings, lists, tuples, sets, dictionaries, and other iterable objects. They are especially useful when validating input, checking collection contents, comparing object references, and controlling program execution.

Python provides two membership operators:

  • in – Returns True if a value is found in a collection or sequence.
  • not in – Returns True if a value is not found in a collection or sequence.

Python also provides two identity operators:

  • is – Returns True if two references point to the same object.
  • is not – Returns True if two references point to different objects.

2. Learning Objectives

After studying this topic, you should be able to:

  • Understand the purpose of membership and identity operators.
  • Use in and not in with strings and collections.
  • Check for keys in dictionaries using membership operators.
  • Distinguish between object identity and value equality.
  • Use is and is not correctly in Python programs.
  • Understand why is should generally not be used to compare ordinary values.
  • Apply these operators in validation, searching, and conditional statements.

3. What Are Membership Operators?

Membership operators check whether a specified value exists within a sequence or collection. The result of a membership expression is a Boolean value: True or False.

3.1 The in Operator

The in operator checks whether an item exists in a collection or sequence. It returns True when the item is found and False otherwise.

fruits = ["apple", "banana", "mango"]

print("apple" in fruits)
print("orange" in fruits)

Output:

True
False

In this example, "apple" is present in the list, while "orange" is not.

3.2 The not in Operator

The not in operator checks whether an item is absent from a collection or sequence. It returns True when the item is not found.

colors = ["red", "green", "blue"]

print("yellow" not in colors)
print("red" not in colors)

Output:

True
False

The first expression returns True because "yellow" is absent. The second returns False because "red" is present.

4. Membership Operators with Strings

Strings are sequences of characters. Membership operators can check whether a character or substring occurs inside a string.

message = "Learn Python Programming"

print("Python" in message)
print("Java" in message)
print("Learn" not in message)
print("Code" not in message)

Output:

True
False
False
True

4.1 Case Sensitivity

String membership checks are case-sensitive. Uppercase and lowercase characters are treated as different characters.

language = "Python"

print("Py" in language)
print("py" in language)
print("PYTHON" in language)

Output:

True
False
False

To perform a case-insensitive check, convert the strings to the same case before testing membership.

language = "Python Programming"
search_term = "PYTHON"

print(search_term.lower() in language.lower())

Output:

True

5. Membership Operators with Lists and Tuples

Lists and tuples can contain multiple values. The in operator checks whether an item matches an element in the collection. The not in operator checks whether no matching element is present.

5.1 Using Membership Operators with Lists

numbers = [10, 20, 30, 40, 50]

print(30 in numbers)
print(100 in numbers)
print(60 not in numbers)

Output:

True
False
True

5.2 Using Membership Operators with Tuples

days = ("Monday", "Tuesday", "Wednesday")

print("Tuesday" in days)
print("Sunday" not in days)

Output:

True
True

5.3 Membership Checks with Nested Lists

When a list contains other lists, membership checks operate on the top-level elements. They do not automatically search inside nested lists.

matrix = [[1, 2], [3, 4], [5, 6]]

print([1, 2] in matrix)
print(1 in matrix)
print(1 in matrix[0])

Output:

True
False
True

The integer 1 is not a top-level element of matrix; it is inside the first nested list. Therefore, 1 in matrix returns False.

6. Membership Operators with Sets

A set stores unique elements and supports membership checks. Checking membership in a set is generally efficient, making sets useful for testing whether values exist in a collection.

allowed_roles = {"admin", "editor", "viewer"}

print("admin" in allowed_roles)
print("guest" in allowed_roles)
print("guest" not in allowed_roles)

Output:

True
False
True

Sets are useful when you need to check membership frequently, such as verifying permissions, detecting duplicate candidates, or validating category names.

7. Membership Operators with Dictionaries

When membership operators are used with a dictionary, they check its keys by default, not its values.

student = {
    "name": "Aarav",
    "age": 21,
    "course": "Python"
}

print("name" in student)
print("Python" in student)
print("Python" in student.values())
print("Aarav" in student.values())

Output:

True
False
True
True

The expression "Python" in student returns False because "Python" is a value rather than a key. To check dictionary values, use student.values(). To check keys explicitly, use student.keys().

7.1 Checking Dictionary Keys and Values

employee = {
    "id": 101,
    "name": "Riya",
    "department": "IT"
}

if "department" in employee:
    print("Department key exists")

if "HR" not in employee.values():
    print("HR is not a stored value")

Output:

Department key exists
HR is not a stored value

8. Membership Operators with Different Data Types

Data Type Example Explanation
String "cat" in "catalog" Checks whether a substring exists.
List 5 in [1, 5, 9] Checks whether an element exists in a list.
Tuple "red" in ("red", "blue") Checks whether an element exists in a tuple.
Set 10 in {10, 20, 30} Checks whether an element exists in a set.
Dictionary "id" in {"id": 1} Checks dictionary keys by default.
Range 4 in range(1, 6) Checks whether a number belongs to the range.

Membership tests require a suitable iterable or container. Attempting to check membership in an unsupported object can raise a TypeError.

9. Practical Examples of Membership Operators

9.1 Validating User Input

valid_choices = ["yes", "no"]

choice = input("Enter yes or no: ").strip().lower()

if choice in valid_choices:
    print("Valid choice")
else:
    print("Invalid choice")

This program checks whether the entered choice is one of the accepted values.

9.2 Checking for a Restricted Word

message = input("Enter a message: ").lower()
restricted_words = ["spam", "scam", "fraud"]

if any(word in message for word in restricted_words):
    print("The message contains a restricted word")
else:
    print("No restricted words detected")

The any() function returns True if at least one of the membership tests is true. This example performs simple substring detection, not advanced word-boundary matching.

9.3 Checking a Number in a Range

number = 7

if number in range(1, 11):
    print("Number is between 1 and 10")
else:
    print("Number is outside the range")

Output:

Number is between 1 and 10

10. What Are Identity Operators?

Identity operators determine whether two expressions refer to the exact same object. They do not simply check whether two values are equal.

Python provides two identity operators:

  • is – Returns True when both references point to the same object.
  • is not – Returns True when the references point to different objects.

Identity is different from equality. Two separate objects can contain equal values but still be different objects.

11. The is Operator

The is operator checks whether two references identify the same object.

first_list = [1, 2, 3]
second_list = first_list

print(first_list is second_list)

Output:

True

Both variables refer to the same list object. Changing the list through either variable affects the same underlying object.

first_list = [1, 2, 3]
second_list = first_list

second_list.append(4)

print(first_list)
print(second_list)

Output:

[1, 2, 3, 4]
[1, 2, 3, 4]

12. The is not Operator

The is not operator checks whether two references point to different objects.

first_list = [10, 20, 30]
second_list = [10, 20, 30]

print(first_list is not second_list)

Output:

True

Although the lists contain the same values, Python creates two separate list objects in this example. Therefore, they are not identical.

13. Difference Between Identity and Equality

Python uses the equality operator == to compare values and the identity operator is to compare object identity.

list_a = [1, 2, 3]
list_b = [1, 2, 3]
list_c = list_a

print(list_a == list_b)
print(list_a is list_b)
print(list_a == list_c)
print(list_a is list_c)

Output:

True
False
True
True

Explanation:

  • list_a == list_b is True because both lists contain equal values.
  • list_a is list_b is False because the lists are separate objects.
  • list_a == list_c is True because they refer to lists with equal contents.
  • list_a is list_c is True because list_c refers to the same object as list_a.

13.1 Comparison Table

Operator Purpose Question Answered Example
== Value equality Do these objects have equal values? [1, 2] == [1, 2] returns True.
!= Value inequality Are these values unequal? 5 != 8 returns True.
is Object identity Are these references to the same object? a is b
is not Non-identity Are these references to different objects? a is not b

14. Using Identity Operators with None

The None value represents the absence of a value or a missing result. Python programmers should normally use is None or is not None when checking for it.

result = None

if result is None:
    print("No result is available")
else:
    print("Result is available")

Output:

No result is available

To check whether a variable has a non-None value, use:

username = "Aarav"

if username is not None:
    print("Username has been provided")

Output:

Username has been provided

Prefer is None over == None because identity checking is the conventional and reliable way to test for the singleton None object.

15. Why You Should Not Normally Use is for Value Comparisons

A common beginner mistake is using is to compare strings, numbers, or other values. Python may reuse certain immutable objects internally, but this behavior should not be relied upon for application logic.

value_a = 1000
value_b = 1000

print(value_a == value_b)
print(value_a is value_b)

The equality comparison is expected to return True because the integer values are equal. The identity result should not be relied upon because object reuse is an implementation detail and can vary with context or Python implementation.

For ordinary value comparisons, use == and !=. Use is and is not when object identity is what matters, particularly for checks against None.

16. Identity Operators with Mutable and Immutable Objects

Mutable objects, such as lists and dictionaries, can be modified after creation. Immutable objects, such as strings, integers, and tuples, cannot be modified in place. Mutability does not determine whether two references are identical; identity depends on whether they point to the same object.

16.1 Mutable Object Example

original = {"name": "Riya"}
alias = original

print(original is alias)

alias["name"] = "Anaya"

print(original)

Output:

True
{'name': 'Anaya'}

Both variables refer to the same dictionary. Updating the dictionary through alias also changes what is observed through original.

16.2 Separate Objects with Equal Values

original = {"name": "Riya"}
copy = original.copy()

print(original == copy)
print(original is copy)

Output:

True
False

The copied dictionary contains equal values, but it is a separate dictionary object.

17. Using Membership and Identity Operators Together

Membership and identity operators solve different problems, but they can be used together in the same conditional statement.

users = ["Aarav", "Riya", "Anaya"]
current_user = "Riya"
previous_user = None

if current_user in users and previous_user is None:
    print("Valid current user and no previous user")

Output:

Valid current user and no previous user

The membership operator checks whether the current username is in the list. The identity operator checks whether previous_user is None.

18. Membership and Identity Operators in Conditional Statements

These operators are often used with if, elif, and else statements to control program flow.

permissions = {"read", "write"}
requested_permission = "read"
user_token = None

if requested_permission in permissions and user_token is not None:
    print("Access granted")
elif requested_permission not in permissions:
    print("Permission denied")
else:
    print("Authentication token is missing")

Output:

Authentication token is missing

The first condition is false because the token is None. The second condition is also false because the requested permission exists in the set. Python therefore executes the else block.

19. Operator Precedence and Boolean Expressions

Membership and identity expressions can be combined with logical operators such as and, or, and not. Parentheses can make complex expressions easier to read and help prevent logic mistakes.

allowed_extensions = {".py", ".txt", ".csv"}
filename = "report.csv"
user_id = None

if filename.endswith(".csv") and user_id is None:
    print("CSV file selected and user ID is missing")

if filename.endswith(".csv") and (".csv" in allowed_extensions):
    print("File extension is allowed")

Output:

CSV file selected and user ID is missing
File extension is allowed

Use parentheses whenever a Boolean expression becomes difficult to understand. Clear expressions are easier to test, maintain, and debug.

20. Common Mistakes and Troubleshooting

Mistake Why It Is a Problem Correct Approach
Using is to compare ordinary values Identity does not mean value equality. Use == for equal values.
Checking a dictionary value with value in dictionary Dictionary membership checks keys by default. Use value in dictionary.values().
Ignoring string case sensitivity "python" does not match "Python" directly. Normalize both strings with lower() or casefold().
Searching inside nested lists incorrectly Membership checks the top-level elements of a list. Check the appropriate nested list or iterate through the structure.
Using membership with a non-iterable object The expression may raise TypeError. Check a supported collection or use an appropriate validation method.
Assuming is results for numbers are fixed Object reuse can depend on implementation details. Use value equality for numeric comparisons.
Confusing a missing value with a falsy value Values such as 0, False, and "" are not None. Use is None when specifically checking for None.

21. Best Practices

  • Use in when checking whether an element exists in a collection.
  • Use not in when checking that an element is absent.
  • Remember that dictionary membership checks keys by default.
  • Use sets for frequent membership checks when their unique-element behavior fits the problem.
  • Use == and != to compare ordinary values.
  • Use is None and is not None to test for the absence of a value.
  • Do not rely on object interning or memory reuse when writing comparisons.
  • Normalize strings when a case-insensitive membership test is required.
  • Use descriptive variable names and parentheses to make conditions readable.
  • Test edge cases, including empty collections, missing dictionary keys, and None values.

22. Performance Considerations

The time required for a membership check depends on the data structure and its implementation.

Collection Typical Membership Performance Important Note
List O(n) May inspect elements one by one until a match is found.
Tuple O(n) Usually searches elements sequentially.
Set O(1) average Uses hashing; performance can degrade in unusual collision-heavy cases.
Dictionary keys O(1) average Membership checks dictionary keys using hashing.
String Depends on string length and implementation Checks for a character or substring within the text.

For small collections, a list is often perfectly suitable. For large collections with frequent membership checks, a set or dictionary may be more efficient if the data and requirements allow it.

23. Practical Mini Project: User and Permission Validator

This mini project combines membership and identity operators to check a username, verify a requested permission, and detect a missing authentication token.

registered_users = {"aarav", "riya", "anaya"}
allowed_permissions = {"read", "write"}

username = input("Enter username: ").strip().lower()
permission = input("Enter permission (read/write): ").strip().lower()
token = None

if username not in registered_users:
    print("User is not registered")
elif permission not in allowed_permissions:
    print("Permission is not allowed")
elif token is None:
    print("Authentication token is missing")
else:
    print("Access granted")

Project Explanation

  • The in and not in operators verify whether the username and permission are recognized.
  • The token is None expression checks whether the token is missing.
  • The conditional statements stop at the first matching branch.
  • The program demonstrates basic validation only; real authentication requires secure token creation, verification, expiration handling, and appropriate access controls.

24. Practice Exercises

  1. Create a list of five programming languages and check whether Python exists in the list.
  2. Write a program that checks whether a user-entered character exists in a string.
  3. Create a dictionary containing a person's name, age, and city. Check for the existence of each key.
  4. Check whether a number exists in range(1, 21).
  5. Create two lists with identical values and compare them using both == and is.
  6. Create two variables that refer to the same dictionary and demonstrate object identity.
  7. Write a program that checks whether a variable is None.
  8. Build a simple login-input validator using membership operators.
  9. Create a set of permitted file extensions and check whether a filename's extension is allowed.
  10. Write a program that combines membership, identity, and logical operators in a single condition.

25. Interview Questions and Answers

Q1. What are membership operators in Python?

Answer: Membership operators check whether an item exists in a collection or sequence. Python provides in and not in.

Q2. What is the difference between in and not in?

Answer: in returns True when the item is found. not in returns True when the item is absent.

Q3. What are identity operators?

Answer: Identity operators check whether two references point to the same object. Python provides is and is not.

Q4. What is the difference between == and is?

Answer: The == operator compares values for equality, while is checks whether both references point to the same object.

Q5. Why should is None be used instead of == None?

Answer: None is a singleton object, so identity checking is the conventional and reliable way to test whether a variable refers to it.

Q6. How does membership work with dictionaries?

Answer: Membership checks dictionary keys by default. Use dictionary.values() to check values or dictionary.items() to inspect key-value pairs.

Q7. Can two objects be equal but not identical?

Answer: Yes. Two separately created lists can contain the same values, making them equal with == but not identical with is.

Q8. Is membership checking case-sensitive for strings?

Answer: Yes. String membership is case-sensitive unless the strings are normalized before comparison.

Q9. What does value not in collection mean?

Answer: It checks whether the value is absent from the collection and returns a Boolean result.

Q10. When is a set useful for membership testing?

Answer: A set is useful when frequent membership checks are needed and unique elements are appropriate. Set membership has average O(1) time complexity.

Q11. Does in check dictionary keys or values?

Answer: It checks keys by default. To check values, use value in dictionary.values().

Q12. Can is be used to compare strings and integers?

Answer: It can evaluate object identity for those objects, but it should not normally be used to compare their values. Use == instead.

26. Quick Revision Checklist

  • in checks whether an element exists.
  • not in checks whether an element is absent.
  • is checks whether two references point to the same object.
  • is not checks whether two references point to different objects.
  • Use == for value equality.
  • Dictionary membership checks keys by default.
  • String membership is case-sensitive.
  • Use is None to test for None.
  • Lists and tuples generally require sequential membership searches.
  • Sets and dictionary keys generally provide average O(1) membership checks.
  • Identity and equality are different concepts.

27. Conclusion

Membership and identity operators are important parts of Python's operator system. The in and not in operators help determine whether values exist within strings and collections, while is and is not check object identity.

The most important distinction to remember is that equality compares values, whereas identity compares object references. Use membership operators for searching and validation, use equality operators for ordinary value comparisons, and use identity checks especially when testing for None. Practicing these concepts will help you write clearer, safer, and more efficient Python programs.

Continue Learning: Explore the Python Training Course, register for a course demo, or visit the JustAcademy homepage.

whatsapp