PYTHON
Leverage Python Sets for Unique Items and Data Operations
Discover how to use Python sets to easily find unique elements, perform efficient intersection, union, and difference operations, ideal for managing distinct data points.
user_roles = ['admin', 'editor', 'viewer', 'admin', 'auditor']
all_permissions = ['read', 'write', 'delete', 'read', 'execute']
# 1. Get unique roles
unique_roles = set(user_roles)
print(f"Unique Roles: {unique_roles}")
# 2. Add an element to a set
unique_roles.add('moderator')
print(f"Roles after adding: {unique_roles}")
# 3. Set union: all unique permissions from two sources
backend_perms = {'read', 'write', 'execute'}
frontend_perms = {'read', 'render', 'style'}
combined_perms = backend_perms.union(frontend_perms)
print(f"Combined Permissions (Union): {combined_perms}")
# 4. Set intersection: common permissions
common_perms = backend_perms.intersection(frontend_perms)
print(f"Common Permissions (Intersection): {common_perms}")
# 5. Set difference: permissions unique to backend
backend_only_perms = backend_perms.difference(frontend_perms)
print(f"Backend Only Permissions (Difference): {backend_only_perms}")
How it works: Python sets are unordered collections of unique elements. They are incredibly efficient for checking membership (`item in my_set` is `O(1)` on average), removing duplicates, and performing mathematical set operations like union, intersection, and difference. This makes them ideal for tasks such as managing unique tags, user permissions, or comparing data sources in web development.