How to Find the Intersection of Permission Sets in Python

This code defines a function that takes a list of permission sets and returns a set containing only the permissions common to all sets, with a short-circuit for empty results.

Easy Python 3.9+ Aug 9, 2026 Dictionaries & sets 12 views 0 copies

Python code

24 lines
Python 3.9+
from typing import Set

def intersect_permissions(permission_sets: list[Set[str]]) -> Set[str]:
    """
    Given a list of permission sets, return the common permissions
    present in every set.
    """
    if not permission_sets:
        return set()
    
    common = permission_sets[0]
    for perm_set in permission_sets[1:]:
        common = common.intersection(perm_set)
        if not common:
            break
    return common

if __name__ == "__main__":
    admin_perms = {"read", "write", "delete", "execute"}
    editor_perms = {"read", "write", "edit"}
    viewer_perms = {"read", "view"}
    
    result = intersect_permissions([admin_perms, editor_perms, viewer_perms])
    print(f"Common permissions: {sorted(result)}")

Output

stdout
Common permissions: ['read']

How it works

The function starts by checking if the input list is empty, returning an empty set to avoid an IndexError. It initializes common with the first set and then iterates over the remaining sets, updating common with the intersection of itself and the current set. Using set.intersection returns a new set containing elements present in both sets. The early break when common becomes empty optimizes performance by stopping the loop once no common permissions remain. The type hints with Set[str] clarify that the function works with sets of strings, and the example in the __main__ block demonstrates typical usage.

Common mistakes

  • Forgetting to handle the empty list case, which raises an IndexError
  • Modifying the original sets by using `intersection_update` instead of `intersection`
  • Assuming order of set elements, which is not guaranteed in Python

Variations

  1. Use `functools.reduce(set.intersection, permission_sets)` for a concise one-liner
  2. Use the `&` operator: `common &= perm_set` for in-place intersection

Real-world use cases

  • Checking which API endpoints a group of users with different roles can all access.
  • Finding common file permissions across multiple user groups in a shared filesystem.
  • Determining overlapping feature flags enabled across all environments in a deployment config.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Dictionaries & sets

Related tutorials and quizzes for this topic.