Search code examples
pythonsetunique

How can I test several sets for items that are unique in Python?


I'm looking for a way to find the unique items between several sets. For example, take these 3 sets.

x = {1, 2}
y = {1, 3}
z = {1, 3, 4, 5}

How can I find the unique items? I'm looking for something like this.

findunique(x, y, z) # {2, 4, 5}

I tried using symmetric_difference with reduce, but that ended up returning {1, 2, 4, 5}.

The only other thing I can think of is to have a dict keep track of how many counts there are for each item, and return only the ones with 1 count. However, that seems very inefficient and unpythonic. What's the "right" way to go about this?


Solution

  • Combine the sets into one list with chain. Count the number of occurrences of each item with Counter. Select the items that occur only once and make a set of them.

    from collections import Counter
    from itertools import chain
    
    sets = x,y,z
    {x for x, cnt in Counter(chain.from_iterable(sets)).items() if cnt==1}
    #{2, 4, 5}
    

    EDITED based on the comments by @jedwards.