Search code examples
pythonsetset-intersection

Finding elements that appear in all sets in a list of sets


I have a list of n sets of integers denoted as lst = [S1, S2, S3 ... Sn] and I want to find the intersection of all the sets.

Is there an optimal way to do this?


Solution

  • If you have a list sets, you can trivially get their intersection with:

    set.intersection(*lst)
    

    This will produce a new set with only those values that are common between all the sets:

    >>> lst = [{1, 2, 3}, {3, 5}, {2, 3}]
    >>> set.intersection(*lst)
    {3}