Python – Symmetric Difference of Multiple sets
Symmetric Differences among groups of sets are elements that belong to any one of the sets but are not present in any other set. Given a list of sets and the task is to write a Python program to get the symmetric difference of the same.
Input : test_list = [{5, 3, 2, 6, 1}, {7, 5, 3, 8, 2}, {9, 3}, {0, 3, 6, 7}]
Output : {8, 1, 9, 0}
Explanation : 8, 1, 9, 0 occur just 1 time over whole container.
Input : test_list = [{5, 3, 2, 6, 1}, {7, 5, 3, 8, 2}, {9, 3}]
Output : {8, 1, 9}
Explanation : 8, 1, 9 occur just 1 time over whole container.
Method #1: Using Counter() + chain.from_iterable()
This method is used to check for all elements that have 1 as frequency overall sets by flattening. Counter() extracts frequencies and then all elements with count 1 can be extracted.
Python3
# Python3 code to demonstrate working of# Symmetric Difference of Multiple sets# Using Counter() + chain.from_iterable() from collections import Counterfrom itertools import chain # initializing listtest_list = [{5, 3, 2, 6, 1}, {7, 5, 3, 8, 2}, {9, 3}, {0, 3, 6, 7}] # printing original listprint("The original list is : " + str(test_list)) # getting frequencies using Counter()# from_iterable() flattens the list freq = Counter(chain.from_iterable(test_list)) # getting frequency count 1 res = {idx for idx in freq if freq[idx] == 1} # printing resultprint("Symmetric difference of multiple list : " + str(res)) |
Output:
The original list is : [{1, 2, 3, 5, 6}, {2, 3, 5, 7, 8}, {9, 3}, {0, 3, 6, 7}]
Symmetric difference of multiple list : {8, 1, 9, 0}
Method #2 : Using Counter() + chain.from_iterable() + items()
Similar to above method, only difference being its performed in single step by extracting keys and values using items().
Python3
# Python3 code to demonstrate working of# Symmetric Difference of Multiple sets# Using Counter() + chain.from_iterable() + items()from collections import Counterfrom itertools import chain # initializing listtest_list = [{5, 3, 2, 6, 1}, {7, 5, 3, 8, 2}, {9, 3}, {0, 3, 6, 7}] # printing original listprint("The original list is : " + str(test_list)) # clubbing operations using items() to get items res = {key for key, val in Counter(chain. from_iterable(test_list)). items() if val == 1} # printing resultprint("Symmetric difference of multiple list : " + str(res)) |
Output:
The original list is : [{1, 2, 3, 5, 6}, {2, 3, 5, 7, 8}, {9, 3}, {0, 3, 6, 7}]
Symmetric difference of multiple list : {8, 1, 9, 0}
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course


