Besides not allowing duplicate elements, Python’s set has another very important advantage: it can very quickly check if a specific element exists in the set.
While lists can do the same thing, sets are overwhelmingly faster at checking for existence, especially when the number of elements reaches millions.
This article explains how to use the in operator to check for elements in a set.
The in Operator – Checking for Existence
Using the in operator allows you to get a boolean value of True (exists) or False (does not exist) indicating whether a specified element is in the set.
Syntax:
element in set_variable
Example: Let’s assume we are managing user IDs that are allowed to access a system.
# Set of authorized users
authorized_users = {"u-tanaka", "u-sato", "u-admin", "u-suzuki"}
print(f"Authorized Users Set: {authorized_users}")
# 1. Check for an existing element ("u-admin")
check_admin = "u-admin" in authorized_users
print(f"Does 'u-admin' exist?: {check_admin}")
# 2. Check for a non-existing element ("u-kato")
check_kato = "u-kato" in authorized_users
print(f"Does 'u-kato' exist?: {check_kato}")
Output:
Authorized Users Set: {'u-suzuki', 'u-admin', 'u-tanaka', 'u-sato'}
Does 'u-admin' exist?: True
Does 'u-kato' exist?: False
The not in Operator – Checking for Non-Existence
Conversely, if you want to check that an element does not exist in the set, use the not in operator.
Syntax:
element not in set_variable
Example:
# Is "u-kato" NOT in the authorized users set?
check_kato_not_in = "u-kato" not in authorized_users
print(f"Does 'u-kato' NOT exist?: {check_kato_not_in}")
Output:
Does 'u-kato' NOT exist?: True
Using in if Statements
The in operator is most commonly used in if statement conditions. This allows you to concisely write logic like “If the user is in the authorized users set…”.
def check_access(user_id):
"""
Determine if user_id is in the authorized set
"""
if user_id in authorized_users:
print(f"Welcome, {user_id}. Access granted.")
else:
print(f"Error: {user_id} does not have access permissions.")
# Execution
check_access("u-sato")
check_access("u-guest")
Output:
Welcome, u-sato. Access granted.
Error: u-guest does not have access permissions.
Summary
- Use the
inoperator to check if an element exists in a set. element in setreturnsTrueif found, andFalseotherwise.- Use the
not inoperator to check for non-existence. - Sets perform this existence check much faster than lists.
