Notes
Categories

Membership and Identity Operators in Python [ English ]

< Prev Next >

1. Membership Operators

1.1 Introduction

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

1.2 Types of Membership Operators

Operator Meaning
in Returns True if value is present
not in Returns True if value is not present

1.3 Using in Operator

text = "Python"

print("P" in text)
print("z" in text)

Output

True
False

1.4 Using not in Operator

numbers = [1, 2, 3, 4]

print(5 not in numbers)
print(2 not in numbers)

Output

True
False

1.5 Membership in Different Data Types

List

nums = [10, 20, 30]
print(20 in nums)

String

print("Py" in "Python")

Dictionary

student = {"name": "Rahul", "age": 20}

print("name" in student)

Explanation

1.6 Key Points

2. Identity Operators

2.1 Introduction

Identity operators are used to compare whether two variables refer to the same object in memory.

2.2 Types of Identity Operators

Operator Meaning
is True if both variables refer to same object
is not True if objects are different

2.3 Using is Operator

a = 10
b = 10

print(a is b)

2.4 Using is not Operator

x = [1, 2]
y = [1, 2]

print(x is not y)

2.5 Difference Between == and is

x = [1, 2]
y = [1, 2]

print(x == y)   # compares values
print(x is y)   # compares memory

Output

True
False

2.6 Example with Same Object

a = [1, 2]
b = a

print(a is b)

Output

True

2.7 Key Points

3. Summary

Membership Operators

Identity Operators

< Prev Next >