Python Membership Operators


Membership Operators in Python

Membership operators are used to test whether a value or variable is found in a sequence (like a list, tuple, string, or dictionary). There are two membership operators in Python: in and not in.

List of Membership Operators

OperatorDescriptionExample
inReturns True if the specified value is found in the given sequenceelement in sequence
not inReturns True if the specified value is not found in the given sequenceelement not in sequence

Examples of Membership Operators

1. Using the in Operator

The in operator checks if a value exists in a sequence.

# Example with a list fruits = ['apple', 'banana', 'cherry'] print('banana' in fruits) # Output: True print('grape' in fruits) # Output: False # Example with a string text = "Hello, world!" print('Hello' in text) # Output: True print('hello' in text) # Output: False (case-sensitive)

2. Using the not in Operator

The not in operator checks if a value does not exist in a sequence.

# Example with a list fruits = ['apple', 'banana', 'cherry'] print('grape' not in fruits) # Output: True print('banana' not in fruits) # Output: False # Example with a string text = "Hello, world!" print('earth' not in text) # Output: True print('world' not in text) # Output: False

Examples with Other Data Types

1. Using Membership Operators with Tuples

numbers = (1, 2, 3, 4, 5) print(3 in numbers) # Output: True print(6 not in numbers) # Output: True

2. Using Membership Operators with Dictionaries

When using in with dictionaries, it checks for the presence of keys.

my_dict = {'name': 'Alice', 'age': 25} print('name' in my_dict) # Output: True (key exists) print('Alice' in my_dict) # Output: False (value is not checked)

Summary of Membership Operators:

  • in: Returns True if the specified value is found in the sequence (list, tuple, string, or dictionary).
  • not in: Returns True if the specified value is not found in the sequence.

Membership operators are very useful for quickly checking for the existence of elements within various data structures, making them essential tools for efficient coding in Python.