PYTHON
Find Elements Unique to Either of Two Lists Using Sets
Learn to identify elements that appear in one list but not the other, and vice-versa, by utilizing Python's set symmetric difference operation for data comparison.
list1 = [1, 2, 3, 4, 5, 10]
list2 = [4, 5, 6, 7, 8, 10]
# Convert lists to sets for efficient set operations
set1 = set(list1)
set2 = set(list2)
# Find elements that are in set1 OR set2, but NOT in BOTH
# This is called symmetric difference
unique_to_either = set1.symmetric_difference(set2)
# Alternatively: unique_to_either = set1 ^ set2
print(f"List 1: {list1}")
print(f"List 2: {list2}")
print(f"Elements unique to either list: {sorted(list(unique_to_either))}")
# To get elements only in list1 but not list2 (difference)
only_in_list1 = set1.difference(set2)
print(f"Elements only in List 1: {sorted(list(only_in_list1))}")
# To get elements only in list2 but not list1
only_in_list2 = set2.difference(set1)
print(f"Elements only in List 2: {sorted(list(only_in_list2))}")
# Combining the two differences gives the symmetric difference
combined_differences = only_in_list1.union(only_in_list2)
print(f"Combined differences (union): {sorted(list(combined_differences))}")
How it works: This snippet demonstrates how to find elements that are present in one list but not the other, and vice-versa, using Python's `set` data structure and its symmetric difference operation. By converting lists to sets, these operations become highly efficient. `set1.symmetric_difference(set2)` returns a new set containing all elements that are in either `set1` or `set2`, but not in their intersection. This is useful for identifying unique discrepancies between two collections of items.