PYTHON
Efficient Set Operations for Data Comparison
Learn how to use Python's set operations (union, intersection, difference) for efficiently comparing and manipulating collections of unique data, perfect for web application logic.
user_roles_group_a = {"admin", "editor", "viewer"}
user_roles_group_b = {"editor", "moderator", "viewer"}
# Find all unique roles across both groups
all_roles = user_roles_group_a.union(user_roles_group_b)
# Find roles common to both groups
common_roles = user_roles_group_a.intersection(user_roles_group_b)
# Find roles only in Group A (not in Group B)
group_a_only = user_roles_group_a.difference(user_roles_group_b)
# Find roles only in Group B (not in Group A)
group_b_only = user_roles_group_b.difference(user_roles_group_a)
# Check if a specific role exists in a group
has_admin = "admin" in user_roles_group_a
# print(f"All unique roles: {all_roles}")
# print(f"Roles common to both groups: {common_roles}")
# print(f"Roles only in Group A: {group_a_only}")
# print(f"Roles only in Group B: {group_b_only}")
# print(f"Does Group A have 'admin'? {has_admin}")
How it works: This snippet demonstrates fundamental set operations in Python. Sets are unordered collections of unique elements, making them ideal for tasks like finding common items (intersection), combining unique items (union), or identifying items present in one set but not another (difference). These operations are highly optimized and valuable for managing user permissions, comparing feature flags, or synchronizing data sets efficiently within web applications.