Membership & Identity Operators

  • This lesson explains Membership Operators (in, not in) used to check if a value exists in a sequence, and Identity Operators (is, is not) used to compare memory locations of objects in Python.

  • 1. Membership Operators

    Membership operators are used to check whether a value exists in a sequence such as a list, tuple, string, or dictionary.

    Operator

    Description

    Example

    in

    Returns True if the value is present

    "a" in "apple" → True

    not in

    Returns True if the value is NOT present

    5 not in [1,2,3] → True

Membership Operators Example

Checks whether elements exist inside a list and a string.

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

print("apple in fruits:", "apple" in fruits)
print("grape in fruits:", "grape" in fruits)
print("banana not in fruits:", "banana" not in fruits)

text = "Python"
print("'P' in text:", "P" in text)
print("'z' not in text:", "z" not in text)
  • 2. Identity Operators

    Identity operators are used to compare memory locations of two objects, not their values.

    Operator

    Description

    Example

    is

    Returns True if both variables point to the same object

    a is b

    is not

    Returns True if variables point to different objects

    a is not b


Identity Operators Example

Demonstrates how is and is not compare object identity.

a = [1, 2, 3]
b = a
c = [1, 2, 3]

print("a is b:", a is b)
print("a is c:", a is c)
print("a is not c:", a is not c)

  • Key Differences

    Membership (in)

    Identity (is)

    Checks value presence

    Checks memory location

    Used with lists, strings, tuples

    Used to compare objects

    Compares content

    Compares reference