Membership#

Membership operators are used to verify if a value belongs to a sequence (string, list, tuple, or set), and return a Boolean value (True or False) based on the membership condition.

Operation

Definition

Syntax

in

Return True if value is within the sequence

x=[1,2,3], 2 in x

not in

Return True if value is not within the sequence

x=[1,2,3], 5 not in x

Examples

# String membership
string = "Agricultural and Biological Engineering"
print('biological' in string)        # Output: True
False
print('civil' in string)        # Output: False
False
print('agri' in string)       # Output: True
False
print('course' not in string)  # Output: False
True
print(3 in my_list)     # Output: True
True
print(6 not in my_list) # Output: True
True
print(5 in my_list[2:]) # Output: True
True
# Define the tuple and check the membership
my_tuple = (10, 20, 30, 40, 50)
print(30 in my_tuple)      # Output: True
True
print(60 not in my_tuple)  # Output: True
True
# Define the set and check the membership
my_set = {1, 2, 3, 4, 5}
print(4 in my_set)     # Output: True
True
print(6 not in my_set) # Output: True
True