0
0
Pythonprogramming~5 mins

Set membership testing in Python

Choose your learning style9 modes available
Introduction

Set membership testing helps you quickly check if something is inside a group of items. It is like asking, "Is this in my collection?"

Checking if a word is in a list of banned words before allowing it.
Seeing if a user ID is in a list of authorized users.
Finding out if a number is part of a set of special numbers.
Deciding if an item is already in your shopping cart.
Syntax
Python
element in set_name

# or

element not in set_name

The in keyword checks if the element is inside the set.

The not in keyword checks if the element is not inside the set.

Examples
Checks if 2 is in the set. It is, so it prints True.
Python
my_set = {1, 2, 3}
print(2 in my_set)  # True
Checks if 'orange' is not in the set. It is not, so it prints True.
Python
my_set = {'apple', 'banana'}
print('orange' not in my_set)  # True
Empty set means nothing is inside, so 5 is not in it.
Python
my_set = set()
print(5 in my_set)  # False
Sample Program

This program checks if 'banana' is in the set and prints a message. Then it checks if 'orange' is not in the set and prints a message.

Python
fruits = {'apple', 'banana', 'cherry'}

item = 'banana'
if item in fruits:
    print(f"Yes, {item} is in the fruit set.")
else:
    print(f"No, {item} is not in the fruit set.")

item = 'orange'
if item not in fruits:
    print(f"No, {item} is not in the fruit set.")
OutputSuccess
Important Notes

Sets are very fast for membership testing compared to lists.

Membership testing works with any data type inside the set, like numbers or strings.

Summary

Use in to check if something is inside a set.

Use not in to check if something is not inside a set.

Sets make membership testing quick and easy.