Python Membership Operators

1. What are Membership Operators?

Membership operators are used to check whether a value is present in a group.

In simple words:
πŸ‘‰ They check β€œIs this item inside that group?”

Python has two membership operators:

  • in

  • not in

2. The in Operator

in returns True if the value exists in the group.

Example with String

text = "Python is easy"

print("Python" in text)

Output:

True

Example with List

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

print("apple" in fruits)

Example with Tuple

numbers = (1, 2, 3, 4)

print(3 in numbers)

3. The not in Operator

not in returns True if the value does NOT exist in the group.

Example

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

print("mango" not in fruits)

Output:

True

4. Membership Operators with if Statement

Example

name = "Amit"

if "A" in name:
print("Name contains letter A")

Another Example

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

if "yellow" not in colors:
print("Yellow is not in the list")

5. Membership Operators with User Input

Example

passwords = ["abc123", "python", "hello"]

user_input = input("Enter password: ")

if user_input in passwords:
print("Access granted")
else:
print("Access denied")

6. Membership in Dictionary (Keys Only)

Membership operators check keys, not values.

Example

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

print("name" in student)
print("Ravi" in student)

Output:

True
False

7. Common Beginner Mistakes

❌ Checking Value Instead of Key

print("Ravi" in student)

βœ” Correct:

print("name" in student)

❌ Wrong Case in String

print("python" in "Python")

Output:

False

Strings are case-sensitive.

8. Simple Practice Examples

Example 1: Check Letter

word = "hello"
print("h" in word)

Example 2: Check Number in List

nums = [10, 20, 30]

print(25 not in nums)

Example 3: Email Check

email = input("Enter email: ")

if "@" in email:
print("Valid email format")
else:
print("Invalid email format")

9. Summary (Membership Operators)

βœ” Used to check presence
βœ” in means exists
βœ” not in means not exists
βœ” Works with string, list, tuple, dictionary
βœ” Very useful in conditions

πŸ“˜ Perfect for Beginner eBook

This chapter is ideal for:

  • Python beginner books

  • School & college students

  • Self-learners

If you want next, I can write:

  • Bitwise Operators

  • Operator Exercises

  • if–else statements

  • Loops (for, while)

  • MCQs with answers

Just tell me 😊

You may also like...